Image resizing with GDI+

前端 未结 3 1494
[愿得一人]
[愿得一人] 2021-01-24 02:35

I\'m really trying to nail out a little more performance out of this tidbit of code. It\'s not a heavly used bit of code but is used every time a new image is uploaded, and 4 ti

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-24 03:25

    For completeness, here is the solution to the second part of the question which was never answered. When processing a low resolution image the image was being cut off. The solution now, seems obvious. The problem lies in this bit of code from above:

    using (Bitmap newImage = new Bitmap(newSize.Width, newSize.Height, 
                                                        PixelFormat.Format32bppRgb))
    

    The problem being that I'm selecting the PixelFormat, not letting it be the format of the original image. The correct code is here:

    public static byte[] ResizeImageFile(byte[] imageFile, int targetSize)
    {
        using (System.Drawing.Image oldImage = System.Drawing.Image.FromStream(new MemoryStream(imageFile)))
        {
            Size newSize = CalculateDimensions(oldImage.Size, targetSize);
    
        using (Bitmap newImage = new Bitmap(newSize.Width, newSize.Height,  
                                                            oldImage.PixelFormat))
        {
            newImage.SetResolution(oldImage.HorizontalResolution, 
                                                       oldImage.VerticalResolution);
            using (Graphics canvas = Graphics.FromImage(newImage))
            {
                canvas.SmoothingMode = SmoothingMode.AntiAlias;
                canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
                canvas.PixelOffsetMode = PixelOffsetMode.HighQuality;
                canvas.DrawImage(oldImage, new Rectangle(new Point(0, 0), newSize));
                MemoryStream m = new MemoryStream();
                newImage.Save(m, ImageFormat.Jpeg);
                return m.GetBuffer();
            }
        }
    
       }
    }
    

提交回复
热议问题