c# - 调整图像文件大小时,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();
}
}
}
}
找了好久的答案,求大神帮忙。谢谢
解决方案
由于未显示CalculateDimensions和ConvertToBytes方法,我试图假设上述方法如下所示:
// 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;
}
如果你的代码不能正常工作,那么一定是上面的方法有一些问题。
推荐阅读
- ios - 如何快速更改启动屏幕图像?
- python - Python list.pop(i) 时间复杂度?
- javascript - 当用户在加载的页面(NextJS、ReactJS)之间导航时,加载指示器不显示
- fortran - 这个语法在 fortran 中是什么意思?
- laravel - Laravel - 限制用户的帖子数量
- ios - 如何在 Flutter 中覆盖supportedInterfaceOrientations?
- character-encoding - Notepad++更新到Windows 10 18363.592后无法显示汉字
- php - 重试模式,如何确定 PHP 中的失败类型
- database - 在规范化之前将原始表划分为子表?
- python - 如何在 Ebay 中迭代页面