C# 下载时如何调整图像大小?

C# 下载时如何调整图像大小?,c#,asp.net,image,resize,download,C#,Asp.net,Image,Resize,Download,我想在下载图像时或下载后调整图像大小。这是我的密码。质量并不重要 public void downloadPicture(string fileName, string url,string path) { string fullPath = string.Empty; fullPath = path + @"\" + fileName + ".jpg"; //imagePath byte[] content; HttpWebReq

我想在下载图像时或下载后调整图像大小。这是我的密码。质量并不重要

public void downloadPicture(string fileName, string url,string path) {
        string fullPath = string.Empty;
        fullPath = path + @"\" + fileName + ".jpg"; //imagePath
        byte[] content;
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        WebResponse response = request.GetResponse();

        Stream stream = response.GetResponseStream();

        using (BinaryReader br = new BinaryReader(stream)) {
            content = br.ReadBytes(500000);
            br.Close();
        }
        response.Close();

        FileStream fs = new FileStream(fullPath, FileMode.Create); // Starting create
        BinaryWriter bw = new BinaryWriter(fs);
        try {
            bw.Write(content); // Created
        }
        finally {
            fs.Close();
            bw.Close();
        }
    }

那个么我该怎么做呢?

图像大小调整表面上看起来很简单,但一旦开始工作就会涉及很多复杂问题。我建议你不要自己做这件事,去一个像样的图书馆

您可以使用,它是一个非常简单、开源和免费的库

您可以使用Nuget或进行安装


将此代码放在try/finally块之后-

这会将图像大小调整为其原始大小的1/4

        using (System.Drawing.Image original = System.Drawing.Image.FromFile(fullPath))
        {
            int newHeight = original.Height / 4;
            int newWidth = original.Width / 4;

            using (System.Drawing.Bitmap newPic = new System.Drawing.Bitmap(newWidth, newHeight))
            {
                using (System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(newPic))
                {
                    gr.DrawImage(original, 0, 0, (newWidth), (newHeight));
                    string newFilename = ""; /* Put new file path here */
                    newPic.Save(newFilename, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
            }
        }
当然,您可以通过更改newHeight和newWidth变量将其更改为您想要的任何大小


更新:根据下面的注释,将代码修改为使用(){}而不是dispose。

您可以使用
Image.FromFile(字符串)
获取一个
图像
对象,此站点有一个扩展方法来实际调整图像大小。

在我制作的应用程序中,有必要创建一个具有多个选项的函数。它相当大,但可以调整图像的大小,可以保持纵横比,并可以切割边缘以仅返回图像的中心:

/// <summary>
    /// Resize image with an URL as source
    /// </summary>
    /// <param name="OriginalFileURL">Link to the image</param>
    /// <param name="heigth">new height</param>
    /// <param name="width">new width</param>
    /// <param name="keepAspectRatio">keep the aspect ratio</param>
    /// <param name="getCenter">return the center bit of the image</param>
    /// <returns>image with new dimentions</returns>
    public Image resizeImageFromURL(String OriginalFileURL, int heigth, int width, Boolean keepAspectRatio, Boolean getCenter)
    {
        int newheigth = heigth;
        WebResponse response = null;
        try
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(OriginalFileURL);
            response = request.GetResponse();
        }
        catch
        {
            return (System.Drawing.Image) new Bitmap(1, 1);
        }
        Stream imageStream = response.GetResponseStream();

        System.Drawing.Image FullsizeImage = System.Drawing.Image.FromStream(imageStream);

        // Prevent using images internal thumbnail
        FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
        FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);

        if (keepAspectRatio || getCenter)
        {
            int bmpY = 0;
            double resize = (double)FullsizeImage.Width / (double)width;//get the resize vector
            if (getCenter)
            {
                bmpY = (int)((FullsizeImage.Height - (heigth * resize)) / 2);// gives the Y value of the part that will be cut off, to show only the part in the center
                Rectangle section = new Rectangle(new System.Drawing.Point(0, bmpY), new System.Drawing.Size(FullsizeImage.Width, (int)(heigth * resize)));// create the section to cut of the original image
                Bitmap orImg = new Bitmap((Bitmap)FullsizeImage);//for the correct effect convert image to bitmap.
                FullsizeImage.Dispose();//clear the original image
                using (Bitmap tempImg = new Bitmap(section.Width, section.Height))
                {
                    Graphics cutImg = Graphics.FromImage(tempImg);//              set the file to save the new image to.
                    cutImg.DrawImage(orImg, 0, 0, section, GraphicsUnit.Pixel);// cut the image and save it to tempImg
                    FullsizeImage = tempImg;//save the tempImg as FullsizeImage for resizing later
                    orImg.Dispose();
                    cutImg.Dispose();
                    return FullsizeImage.GetThumbnailImage(width, heigth, null, IntPtr.Zero);
                }
            }
            else newheigth = (int)(FullsizeImage.Height / resize);//  set the new heigth of the current image
        }//return the image resized to the given heigth and width
        return FullsizeImage.GetThumbnailImage(width, newheigth, null, IntPtr.Zero);
    }

几天前我问了同样的问题,我被引导到这个线程,但实际上我自己的情况是,我想调整位图图像的大小。我的意思是,您可以将下载的流转换为bitmapImage,然后调整大小,如果只指定宽度或高度,即

public static async void DownloadImagesAsync(BitmapImage list, String Url)
{
   try
   {
       HttpClient httpClient = new HttpClient();
       // Limit the max buffer size for the response so we don't get overwhelmed
       httpClient.MaxResponseContentBufferSize = 256000;
       httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (compatible; MSIE           10.0; Windows NT 6.2; WOW64; Trident/6.0)");
       HttpResponseMessage response = await httpClient.GetAsync(Url);
       response.EnsureSuccessStatusCode();
       byte[] str = await response.Content.ReadAsByteArrayAsync();
       InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
       DataWriter writer = new DataWriter(randomAccessStream.GetOutputStreamAt(0));
       writer.WriteBytes(str);
       await writer.StoreAsync();
       BitmapImage img = new BitmapImage();
       img.SetSource(randomAccessStream);
       //img.DecodePixelHeight = 92;
       img.DecodePixelWidth = 60; //specify only width, aspect ratio maintained
       list.ImageBitmap = img;                   
   }catch(Exception e){
      System.Diagnostics.Debug.WriteLine(ex.StackTrace);
   }
}

from

fullPath=path+@“\”+文件名+“RESIZE.jpg”;字符串newFilename=fullPath.Replace(“RESIZE”,”);文件删除(完整路径);我添加了它们,效果非常好。感谢-1没有使用
using(){}
,GDI操作可能会任意失败并导致内存泄漏,这反过来会触发更多异常和额外泄漏的内存,直到服务器崩溃。NET GC不知道GDI对象,如图像、图形或位图。它们在非托管堆中分配几十兆字节的RAM,而.NET是不可见的。一张500KB的12MP图像需要48MB的连续RAM才能被简单解码。@计算机语言学家同意,谢谢你的提示,修改后的代码供将来谷歌参考:)
/// <summary>
    /// Resize image with an URL as source
    /// </summary>
    /// <param name="OriginalFileURL">Link to the image</param>
    /// <param name="heigth">new height</param>
    /// <param name="width">new width</param>
    /// <returns>image with new dimentions</returns>
    public Image resizeImageFromURL(String OriginalFileURL, int heigth, int width)
    {
        return resizeImageFromURL(OriginalFileURL, heigth, width, false, false);
    }

    /// <summary>
    /// Resize image with an URL as source
    /// </summary>
    /// <param name="OriginalFileURL">Link to the image</param>
    /// <param name="heigth">new height</param>
    /// <param name="width">new width</param>
    /// <param name="keepAspectRatio">keep the aspect ratio</param>
    /// <returns>image with new dimentions</returns>
    public Image resizeImageFromURL(String OriginalFileURL, int heigth, int width, Boolean keepAspectRatio)
    {
        return resizeImageFromURL(OriginalFileURL, heigth, width, keepAspectRatio, false);
    }
System.Drawing.Image ResizedImage = resizeImageFromURL(LinkToPicture, 800, 400, true, true);
public static async void DownloadImagesAsync(BitmapImage list, String Url)
{
   try
   {
       HttpClient httpClient = new HttpClient();
       // Limit the max buffer size for the response so we don't get overwhelmed
       httpClient.MaxResponseContentBufferSize = 256000;
       httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (compatible; MSIE           10.0; Windows NT 6.2; WOW64; Trident/6.0)");
       HttpResponseMessage response = await httpClient.GetAsync(Url);
       response.EnsureSuccessStatusCode();
       byte[] str = await response.Content.ReadAsByteArrayAsync();
       InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
       DataWriter writer = new DataWriter(randomAccessStream.GetOutputStreamAt(0));
       writer.WriteBytes(str);
       await writer.StoreAsync();
       BitmapImage img = new BitmapImage();
       img.SetSource(randomAccessStream);
       //img.DecodePixelHeight = 92;
       img.DecodePixelWidth = 60; //specify only width, aspect ratio maintained
       list.ImageBitmap = img;                   
   }catch(Exception e){
      System.Diagnostics.Debug.WriteLine(ex.StackTrace);
   }
}