asp.Net   发布时间:2022-04-07  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了asp.net – MVC3 WebImage助手:resize将透明背景转换为黑色大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试使用MVC3的Web Image助手创建缩略图.

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

var image = blob.DownloadByteArray();     

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

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

解决方法

上面这个答案很棒,但我做了一些微调并实现了图像的“保持比例”,这样我们就不会得到拉伸的图像了.
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,width,height);
                }
            }
            using (MemoryStream ms = new MemoryStream())
            {
                resizedImage.Save(ms,format);
                return new WebImage(ms.ToArray());
            }
        }
    }

}

大佬总结

以上是大佬教程为你收集整理的asp.net – MVC3 WebImage助手:resize将透明背景转换为黑色全部内容,希望文章能够帮你解决asp.net – MVC3 WebImage助手:resize将透明背景转换为黑色所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。