我正在尝试按如下方式调整图像大小。我将调整后的图像返回到byte[]
,以便我可以将其存储在数据库中。 png图像的透明度丢失了。请帮助改善这一点。
private byte[] GetThumbNail(string imageFile, Stream imageStream,
int imageLen)
{
try
{
Image.GetThumbnailImageAbort imageCallBack =
new Image.GetThumbnailImageAbort(ThumbnailCallback);
Bitmap getBitmap = new Bitmap(imageFile);
byte[] returnByte = new byte[imageLen];
Image getThumbnail = getBitmap.GetThumbnailImage(160, 59,
imageCallBack, IntPtr.Zero);
using (Graphics g = Graphics.FromImage(getThumbnail))
{
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
g.InterpolationMode =
System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.DrawImage(getThumbnail, 0, 0, 160, 59);
}
using (MemoryStream ms = new MemoryStream())
{
getThumbnail.Save(ms, ImageFormat.Png);
getThumbnail.Save("test.png", ImageFormat.Png);
returnByte = ms.ToArray();
}
return returnByte;
}
catch (Exception)
{
throw;
}
}
答案 0 :(得分:25)
您的代码并没有完全符合您的想法......
使用GetThumbnailImage调整图像大小,然后将缩略图图像绘制成自身,这是毫无意义的。您可能在第一步中失去了透明度。
改为创建一个空白位图,并通过在空白位图上绘制来调整源图像的大小。
private byte[] GetThumbNail(string imageFile) {
try {
byte[] result;
using (Image thumbnail = new Bitmap(160, 59)) {
using (Bitmap source = new Bitmap(imageFile)) {
using (Graphics g = Graphics.FromImage(thumbnail)) {
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.DrawImage(source, 0, 0, 160, 59);
}
}
using (MemoryStream ms = new MemoryStream()) {
thumbnail.Save(ms, ImageFormat.Png);
thumbnail.Save("test.png", ImageFormat.Png);
result = ms.ToArray();
}
}
return result;
} catch (Exception) {
throw;
}
}
(我删除了一些从未用于任何与结果有关的参数,比如仅用于创建从未使用的字节数组的imageLen参数。)
答案 1 :(得分:9)
尝试在位图对象上使用.MakeTransparent()
调用。
答案 2 :(得分:2)
可能你应该这样做,因为这件事对我有用:
String path = context.Server.MapPath("/images");
if (!path.EndsWith("\\"))
path += "\\";
path += "none.png";
Image img = CreateThumbnail(Image.FromFile(path));
MemoryStream ms = new MemoryStream();
img.Save(ms, ImageFormat.Png);
ms.WriteTo(context.Response.OutputStream);
private System.Drawing.Image CreateThumbnail(System.Drawing.Image i)
{
int dWidth = i.Width;
int dHeight = i.Height;
int dMaxSize = 150;
if (dWidth > dMaxSize)
{
dHeight = (dHeight * dMaxSize) / dWidth;
dWidth = dMaxSize;
}
if (dHeight > dMaxSize)
{
dWidth = (dWidth * dMaxSize) / dHeight;
dHeight = dMaxSize;
}
return i.GetThumbnailImage(dWidth, dHeight, delegate() { return false; }, IntPtr.Zero);
}