gpt4 book ai didi

asp.net - MVC3 WebImage 助手 : resize is converting transparent background to black

转载 作者:行者123 更新时间:2023-12-04 14:19:21 24 4
gpt4 key购买 nike

我正在尝试使用 MVC3 的 WebImage 助手创建缩略图。

原始图像是具有透明背景的 .png。当我尝试使用以下内容调整大小时:

var image = blob.DownloadByteArray();     

new WebImage(image)
.Resize(50, 50)
.Write();

生成的缩略图将原来的透明背景替换为黑色背景。

最佳答案

上面的答案很好,但我做了一些微调并实现了图像的“保持比例”,这样我们就不会得到拉伸(stretch)的图像。

    using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web.Helpers;

public static class ResizePng
{
private static IDictionary<string, ImageFormat> _transparencyFormats = new Dictionary<string, ImageFormat>(StringComparer.OrdinalIgnoreCase) { { "png", ImageFormat.Png }, { "gif", ImageFormat.Gif } };

public static WebImage ResizePreserveTransparency(this WebImage image, int width, int height)
{
ImageFormat format = null;
if (!_transparencyFormats.TryGetValue(image.ImageFormat, out format))
{
return image.Resize(width, height);
}

//keep ratio *************************************
double ratio = (double)image.Width / image.Height;
double desiredRatio = (double)width / height;
if (ratio > desiredRatio)
{
height = Convert.ToInt32(width / ratio);
}
if (ratio < desiredRatio)
{
width = Convert.ToInt32(height * ratio);
}
//************************************************

using (Image resizedImage = new Bitmap(width, height))
{
using (Bitmap source = new Bitmap(new MemoryStream(image.GetBytes())))
{
using (Graphics g = Graphics.FromImage(resizedImage))
{
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.DrawImage(source, 0, 0, width, height);
}
}
using (MemoryStream ms = new MemoryStream())
{
resizedImage.Save(ms, format);
return new WebImage(ms.ToArray());
}
}
}

}

关于asp.net - MVC3 WebImage 助手 : resize is converting transparent background to black,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4181347/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com