3

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

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();
        }
    }

那么我该怎么做呢?

4

5 回答 5

7

图像调整大小在表面上看起来很简单,但一旦开始工作就会涉及许多复杂性。我建议不要自己做,而是使用像样的图书馆。

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

您可以使用 Nuget 安装它或下载.

使用 nuget 安装

var settings = new ResizeSettings {
  MaxWidth = thumbnailSize,
  MaxHeight = thumbnailSize,
  Format = "jpg"
};

ImageBuilder.Current.Build(inStream, outStream, settings);
resized = outStream.ToArray();
于 2012-05-31T12:35:23.647 回答
4

将此代码放在 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 变量将其更改为您想要的任何大小

更新:修改代码以使用 using() {} 而不是 dispose,如下面的评论。

于 2012-05-31T12:37:22.973 回答
0

几天前我问了同样的问题,我被引导到这个线程,但我自己的情况是我想调整 bitmapImage 的大小。我的意思是,您可以将下载的流转换为 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);
   }
}

源头

于 2013-05-16T10:42:33.477 回答
0

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

/// <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);
    }

为了更容易访问该函数,可以添加一些重载函数:

/// <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);
于 2012-12-18T08:49:21.640 回答
0

您可以使用Image.FromFile(String)来获取Image对象,并且此站点Image Resizing具有扩展方法来实际调整图像大小。

于 2012-05-31T12:41:06.730 回答