二进制图像大小调整出错
Posted
技术标签:
【中文标题】二进制图像大小调整出错【英文标题】:Binary image resizing goes wrong 【发布时间】:2015-09-19 17:28:49 【问题描述】:如果需要,我会尝试将二进制图像调整为更小的文件,但是所有图像在调整大小后都变得越来越多,而尺寸越来越小,所以结果是非常丑陋的图像......不知道为什么它会变大。
这是我使用的代码,任何帮助将不胜感激。
using (var srcImage = System.Drawing.Image.FromStream(myMemStream))
double height = srcImage.Height;
double width = srcImage.Width;
newWidth = (int)(srcImage.Width);
double aspect = scale / width;
newHeight = Convert.ToInt32(aspect * height);
newWidth = Convert.ToInt32(aspect * width);
using (var newImage = new Bitmap(newWidth, newHeight))
using (var graphics = Graphics.FromImage(newImage))
graphics.SmoothingMode = SmoothingMode.AntiAlias;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphics.DrawImage(srcImage, new Rectangle(0, 0, newWidth, newHeight));
System.IO.MemoryStream ms = new System.IO.MemoryStream();
newImage.Save(ms, format);
ms.Position = 0;
_bytes = ms.ToArray(); //Returns a new byte array.
newImage.Dispose();
**** 更新 *****
double height = srcImage.Height;
double width = srcImage.Width;
newWidth = (int)(srcImage.Width);
double aspect = scale / width;
newHeight = Convert.ToInt32(aspect * height);
newWidth = Convert.ToInt32(aspect * width);
Image scaledImage = ScaleDownTo(srcImage, newHeight, newWidth);
newWidth = scaledImage.Width;
newHeight = scaledImage.Height;
System.IO.MemoryStream ms = new System.IO.MemoryStream();
scaledImage.Save(ms, format);
ms.Position = 0;
_bytes = ms.ToArray();
scaledImage.Dispose();
我实际上所做的是将图像调整为静态最大宽度,例如从任意到 300 像素,因此我计算当前图像宽度,将纵横比设为双倍并将此图像调整为这个大小。
对此的任何帮助都非常感谢
【问题讨论】:
【参考方案1】:嗯,这是一个缩小图像的简短函数。
public static Image ScaleDownTo(Image image, int height, int width)
if (image != null)
if (image.Width > width || image.Height > height)
float factor = Math.Max(((float)width) / image.Width, ((float)height) / image.Height);
if (factor > 0)
RectangleF imgRect = new RectangleF(0, 0, image.Width * factor, image.Height * factor);
imgRect.X = ((float)width - imgRect.Width) / 2f;
imgRect.Y = ((float)height - imgRect.Height) / 2f;
Bitmap cellImage = new Bitmap(width, height);
using (Graphics cellImageGraphics = Graphics.FromImage(cellImage))
cellImageGraphics.Clear(Color.Transparent);
cellImageGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
cellImageGraphics.DrawImage(image, imgRect);
return cellImage;
return image;
return null;
只需使用它来获取新的缩小图像。
【讨论】:
你好,试过你的方法,还是一样的问题,看更新以上是关于二进制图像大小调整出错的主要内容,如果未能解决你的问题,请参考以下文章
调整图像大小时出错:“错误:(-215:Assertion failed) func != 0 in function 'resize'”