首页 > 解决方案 > 调整图像文件大小时,GDI+ 中发生一般错误

问题描述

我正在调整图像大小,我的代码可能有什么问题?

var newSize = ResizeImageFile(ConvertToBytes(myFile), 2048);
using (MemoryStream ms = new MemoryStream(newSize, 0, newSize.Length))
{
  ms.Write(newSize, 0, newSize.Length);
  using (Image image = Image.FromStream(ms, true))
  {
    image.Save(targetLocation, ImageFormat.Jpeg);
  }
}

我已使用此功能调整图像大小

public static byte[] ResizeImageFile(byte[] imageFile, int targetSize) // Set targetSize to 1024
        {
            using (Image oldImage = Image.FromStream(new MemoryStream(imageFile)))
            {
                Size newSize = CalculateDimensions(oldImage.Size, targetSize);
                using (Bitmap newImage = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format24bppRgb))
                {
                    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();
                    }
                }
            }
        }

找了好久的答案,求大神帮忙。谢谢

标签: c#asp.net

解决方案


由于未显示CalculateDimensionsConvertToBytes方法,我试图假设上述方法如下所示:

// Calculate the Size at which the image width and height is lower than the specified value
// (Keep the aspect ratio)
private static Size CalculateDimensions(Size size, int targetSize)
{
    double rate = Math.Max(size.Width * 1.0 / targetSize, size.Height * 1.0 / targetSize);
    int w = (int)Math.Floor(size.Width / rate);
    int h = (int)Math.Floor(size.Height / rate);
    return new Size(w, h);
}

//Convert image file to byte array
private static byte[] ConvertToBytes(string fileName)
{
    var result = File.ReadAllBytes(fileName);
    return result;
}

如果你的代码不能正常工作,那么一定是上面的方法有一些问题。


推荐阅读