jquery.imgareaselect实现图片的本地预览和选择截取实现代码

作者:袖梨 2022-06-25

第一还是要引用jquery,接着引用下载好的 jquery.imgareaselect.pack.js 文件和 imgareaselect-default.css 样式文件。

接着写一些元素标签

 代码如下 复制代码
 It's coming right for us!         style="float: left; margin-right: 10px; width: 400px; height: 300px" />
   
   
   
   
   
   
   

这将用来展示图片和记录截取图片的坐标点。

接着开始写js

 代码如下 复制代码


 


上述js完成了本地预览(此处的预览在chrome中正常;在IE中有些问题暂时没有找到本地预览的方法,大家可以用远程方式替换)和截取图片的功能。

前端写完了,接下来开始写后端的代码了

 代码如下 复制代码


 protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                int x1 = Convert.ToInt32(Request["x1"]);
                int y1 = Convert.ToInt32(Request["y1"]);
                int x2 = Convert.ToInt32(Request["x2"]);
                int y2 = Convert.ToInt32(Request["y2"]);


                HttpFileCollection files = Request.Files;
                for (int i = 0; i < files.Count; i++)
                {
                    HttpPostedFile file = files[i];
                    file.SaveAs(Server.MapPath("Upload/" + file.FileName));

                    //设置缩略图
                    int Thumbnailwidth = 400;
                    int Thumbnailheight = 300;
                    //新建一个bmp图片 
                    Bitmap bitmap = new Bitmap(Thumbnailwidth, Thumbnailheight);

                    //新建一个画板 
                    Graphics graphic = Graphics.FromImage(bitmap);

                    //设置高质量插值法 
                    graphic.InterpolationMode = InterpolationMode.High;

                    //设置高质量,低速度呈现平滑程度 
                    graphic.SmoothingMode = SmoothingMode.HighQuality;

                    //清空画布并以透明背景色填充 
                    graphic.Clear(System.Drawing.Color.Transparent);

                    //原图片
                    Bitmap originalImage = new Bitmap(file.InputStream);

                    //在指定位置并且按指定大小绘制原图片的指定部分 
                    graphic.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, Thumbnailwidth, Thumbnailheight),
                        new System.Drawing.Rectangle(0, 0, originalImage.Width, originalImage.Height),
                        System.Drawing.GraphicsUnit.Pixel);

                    //得到缩略图
                    System.Drawing.Image ThumbnailImage = System.Drawing.Image.FromHbitmap(bitmap.GetHbitmap());

                    //创建选择图片
                    Bitmap selectbitmap = new Bitmap(x2-x1, y2-y1);

                    //新建一个画板 
                    Graphics selectgraphic = Graphics.FromImage(selectbitmap);
                  

                    //裁切
                    selectgraphic.DrawImage(ThumbnailImage, 0, 0, new Rectangle(x1, y1, x2 - x1, y2 - y1), GraphicsUnit.Pixel);

                    //保存
                    selectbitmap.Save(Server.MapPath("Upload/"+Guid.NewGuid() + file.FileName), ImageFormat.Jpeg);

                   //todo:将上述资源释放

                }
            }
        }

这里我们先将图片缩小到与前台大图一样的比例,然后在进行截取,并保存到文件中

相关文章

精彩推荐