ASP.NET C#上传图片时,根据选中的内容生成缩略图

我的博客新地址为 http://www.aspx-office.cn/

使用cropper可以在上传图片时,根据用户的选择生成缩略图,参考下图

 



本文就来介绍如何实现上述功能

  在本文解决方案里,图片是通过ImgUrl获取的,这个地址是URL的完全地址,例如请求的地址为

http://localhost:3385/ThumImage/Default.aspx?imgUrl=http://localhost:3385/ThumImage/test.jpg

 因为后面我们将通过该URL获取图片

1)根据远程URL获取远程图片

  这是由 GetResponse实现,代码如下:


    public static Stream GetResponseStream(string url)
    {
        Stream dataStream = null;
    
        try
        {
            WebRequest request = WebRequest.Create(url);
            request.Credentials = CredentialCache.DefaultCredentials;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            if (response.StatusDescription == "OK")
            {
                try
                {
                    dataStream = response.GetResponseStream();
                }
                finally
                {
                  //   dataStream.Close();
                }
            }
          
            return dataStream;
        }
        catch (Exception ex)
        {
            return null;
        }
    }

 

 

2.获取缩略图的X,Y坐标,并生成jpg图片,这是在button_click里实现

 protected void btn_adjust_Click(object sender, EventArgs e)
    {


       //Step1 获取x与y坐标
        int x1, x2, y1, y2;
        x1 = int.Parse(Request.Form["x1"]);
        x2 = int.Parse(Request.Form["x2"]);
        y1 = int.Parse(Request.Form["y1"]);
        y2 = int.Parse(Request.Form["y2"]);

        if ( string.IsNullOrEmpty(Request.QueryString["imgUrl"]))
        {
            return;
        }


        //获取文件流
        Bitmap bt1 = new Bitmap(GetResponse.GetResponseStream(Request.QueryString["imgUrl"]));


        Bitmap bt2 = new Bitmap(90, 120);


        for (int x = 0; x < 90; x++)
        {
            for (int y = 0; y < 120; y++)
            {
                bt2.SetPixel(x, y, bt1.GetPixel(x1 + (x2 - x1) * x /90, y1 + (y2 - y1) * y /120));
            }
        }

        //将要生成的文件名,这里采用硬编码,
        string filename = Server.MapPath(DateTime.Now.ToString("yyyyMMdd")+".jpg");
   
       bt2.Save(filename, System.Drawing.Imaging.ImageFormat.Jpeg);
      

    }

 

这样,就可以把图片保存为小图的jpg格式

 

说明: 如果你需要调整生成图片的大小,需要改动三处

default.aspx里的宽和高,已经后台里的宽和高

详见本文的源代码

 

 

 

ThumImage.rar (123.21 kb)

原文地址:https://www.cnblogs.com/mqingqing123/p/1376400.html