C# 图片等比缩放示例代码

2022-09-16  乐帮网

c#

以下代码是比较推荐的:https://www.cnblogs.com/s0611163/p/6529886.html

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ZoomImage.Utils
{
    /// <summary>
    /// 图片缩放
    /// </summary>
    public class ZoomImageUtil
    {
        #region 图片缩放
        /// <summary>
        /// 图片缩放
        /// </summary>
        /// <param name="bArr">图片字节流</param>
        /// <param name="width">目标宽度,若为0,表示宽度按比例缩放</param>
        /// <param name="height">目标长度,若为0,表示长度按比例缩放</param>
        public static byte[] GetThumbnail(byte[] bArr, int width, int height)
        {
            if (bArr == null) return null;
            MemoryStream ms = new MemoryStream(bArr);
            Bitmap bmp = (Bitmap)Image.FromStream(ms);
            ms.Close();

            bmp = GetThumbnail(bmp, width, height);

            ImageCodecInfo imageCodecInfo = GetEncoder(ImageFormat.Jpeg);
            EncoderParameters encoderParameters = new EncoderParameters(1);
            EncoderParameter encoderParameter = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 75L);
            encoderParameters.Param[0] = encoderParameter;

            ms = new MemoryStream();
            bmp.Save(ms, imageCodecInfo, encoderParameters);
            byte[] result = ms.ToArray();
            ms.Close();
            bmp.Dispose();

            return result;
        }
        #endregion

        #region 图片缩放
        /// <summary>
        /// 图片缩放
        /// </summary>
        /// <param name="bmp">图片</param>
        /// <param name="width">目标宽度,若为0,表示宽度按比例缩放</param>
        /// <param name="height">目标长度,若为0,表示长度按比例缩放</param>
        private static Bitmap GetThumbnail(Bitmap bmp, int width, int height)
        {
            if (width == 0 && height == 0)
            {
                width = bmp.Width;
                height = bmp.Height;
            }
            else
            {
                if (width == 0)
                {
                    width = height * bmp.Width / bmp.Height;
                }
                if (height == 0)
                {
                    height = width * bmp.Height / bmp.Width;
                }
            }

            Image imgSource = bmp;
            Bitmap outBmp = new Bitmap(width, height);
            Graphics g = Graphics.FromImage(outBmp);
            g.Clear(Color.Transparent);
            // 设置画布的描绘质量     
            g.CompositingQuality = CompositingQuality.Default;
            g.SmoothingMode = SmoothingMode.Default;
            g.InterpolationMode = InterpolationMode.Default;
            g.DrawImage(imgSource, new Rectangle(0, 0, width, height + 1), 0, 0, imgSource.Width, imgSource.Height, GraphicsUnit.Pixel);
            g.Dispose();
            imgSource.Dispose();
            bmp.Dispose();
            return outBmp;
        }
        #endregion

        #region 椭圆形缩放
        /// <summary>
        /// 椭圆形缩放
        /// </summary>
        /// <param name="bArr">图片字节流</param>
        /// <param name="width">目标宽度,若为0,表示宽度按比例缩放</param>
        /// <param name="height">目标长度,若为0,表示长度按比例缩放</param>
        public static byte[] GetEllipseThumbnail(byte[] bArr, int width, int height)
        {
            if (bArr == null) return null;
            MemoryStream ms = new MemoryStream(bArr);
            Bitmap bmp = (Bitmap)Image.FromStream(ms);

            Bitmap newBmp = new Bitmap(width, height);
            using (Graphics g = Graphics.FromImage(newBmp))
            {
                using (TextureBrush br = new TextureBrush(bmp))
                {
                    br.ScaleTransform(width / (float)bmp.Width, height / (float)bmp.Height);
                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                    g.FillEllipse(br, new Rectangle(Point.Empty, new Size(width, height)));
                }
            }
            MemoryStream newMs = new MemoryStream();
            newBmp.Save(newMs, System.Drawing.Imaging.ImageFormat.Png);
            byte[] result = newMs.ToArray();

            bmp.Dispose();
            newBmp.Dispose();
            ms.Close();
            newMs.Dispose();

            return result;
        }
        #endregion

        #region GetEncoder
        private static ImageCodecInfo GetEncoder(ImageFormat format)
        {
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.FormatID == format.Guid)
                {
                    return codec;
                }
            }
            return null;
        }
        #endregion

    }
}

下面是收集的其它方法:

//使用方法调用GenerateHighThumbnail()方法即可
//参数oldImagePath表示要被缩放的图片路径
//参数newImagePath表示缩放后保存的图片路径
//参数width和height分别是缩放范围宽和高
public static void GenerateHighThumbnail(string oldImagePath, string newImagePath, int width, int height)
{
	System.Drawing.Image oldImage = System.Drawing.Image.FromFile(oldImagePath);
	int newWidth = AdjustSize(width, height, oldImage.Width, oldImage.Height).Width;
	int newHeight =AdjustSize(width, height, oldImage.Width, oldImage.Height).Height;
	//。。。。。。。。。。。
	System.Drawing.Image thumbnailImage = oldImage.GetThumbnailImage(newWidth, newHeight,new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);
	System.Drawing.Bitmap bm = new System.Drawing.Bitmap(thumbnailImage);
	//处理JPG质量的函数
	System.Drawing.Imaging.ImageCodecInfo ici = GetEncoderInfo("image/jpeg");
	if (ici != null)
	{
		System.Drawing.Imaging.EncoderParameters ep = new System.Drawing.Imaging.EncoderParameters(1);
		ep.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)100);
		bm.Save(newImagePath, ici, ep);
		//释放所有资源,不释放,可能会出错误。
		ep.Dispose();
		ep = null;
	}
	ici = null;
	bm.Dispose();
	bm = null;
	thumbnailImage.Dispose();
	thumbnailImage = null;
	oldImage.Dispose();
	oldImage = null;
}
 
 
private static bool ThumbnailCallback()
{
	return false;
}
 
 
private static ImageCodecInfo GetEncoderInfo(String mimeType)
{
	int j;
	ImageCodecInfo[] encoders;
	encoders = ImageCodecInfo.GetImageEncoders();
	for (j = 0; j < encoders.Length; ++j)
	{
		if (encoders[j].MimeType == mimeType)
		return encoders[j];
	}
	return null;
}
 
 
public struct PicSize
{
	public int Width;
	public int Height;
}
 
 
public static PicSize AdjustSize(int spcWidth, int spcHeight, int orgWidth, int orgHeight)
{
	PicSize size = new PicSize();
	// 原始宽高在指定宽高范围内,不作任何处理 
	if (orgWidth <= spcWidth && orgHeight <= spcHeight)
	{
		size.Width = orgWidth;
		size.Height = orgHeight;
	}
	else
	{
		// 取得比例系数 
		float w = orgWidth / (float)spcWidth;
		float h = orgHeight / (float)spcHeight;
		// 宽度比大于高度比 
		if (w > h)
		{
			size.Width = spcWidth;
			size.Height = (int)(w >= 1 ? Math.Round(orgHeight / w) : Math.Round(orgHeight * w));
		}
		// 宽度比小于高度比 
		else if (w < h)
		{
			size.Height = spcHeight;
			size.Width = (int)(h >= 1 ? Math.Round(orgWidth / h) : Math.Round(orgWidth * h));
		}
		// 宽度比等于高度比 
		else
		{
			size.Width = spcWidth;
			size.Height = spcHeight;
		}
	}
	return size;
}
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;

namespace ResizeImage
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            Resize(args[0], int.Parse(args[1]), int.Parse(args[2]));
            ResizeImageWithAspectRatio(args[0], int.Parse(args[1]), int.Parse(args[2]));
        }

        /// <summary>
        ///     Resize a given image
        /// </summary>
        /// <param name="filePath">input file with path</param>
        /// <param name="width">width of resized image</param>
        /// <param name="height">height of resized image</param>
        private static void Resize(string filePath, int width, int height)
        {
            var file = filePath;
            Console.WriteLine($"Loading {file}");
            using (var imageStream = new FileStream(file, FileMode.Open, FileAccess.Read))
            using (var image = new Bitmap(imageStream))
            {
                var resizedImage = new Bitmap(width, height);
                using (var graphics = Graphics.FromImage(resizedImage))
                {
                    graphics.CompositingMode = CompositingMode.SourceCopy;
                    graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    graphics.CompositingQuality = CompositingQuality.HighSpeed;
                    graphics.DrawImage(image, 0, 0, width, height);
                    var newFilePath = $"{Path.GetDirectoryName(file)}\\{Path.GetFileNameWithoutExtension(file)}_{width}x{height}.png";
                    resizedImage.Save(
                        newFilePath,
                        ImageFormat.Png);
                    Console.WriteLine($"Saving {newFilePath}");
                }
            }
        }
        /// <summary>
        ///  Resize a given image by maintaining the aspect ratio.
        /// </summary>
        /// <param name="filePath">input file with path</param>
        /// <param name="width">width of resized image</param>
        /// <param name="height">height of resized image</param>
        private static void ResizeImageWithAspectRatio(string filePath, int width, int height)
        {
            Console.WriteLine($"Loading {filePath}");
            using (var imageStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            using (var image = new Bitmap(imageStream))
            {
                var thumbnail = new Bitmap(width, height);
                using (var graphic = Graphics.FromImage(thumbnail))
                {
                    graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    graphic.CompositingQuality = CompositingQuality.HighQuality;
                    graphic.SmoothingMode = SmoothingMode.HighQuality;
                    graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;

                    var ratioX = width / (double)image.Width;
                    var ratioY = height / (double)image.Height;

                    var ratio = ratioX < ratioY ? ratioX : ratioY;

                    var newHeight = Convert.ToInt32(image.Height * ratio);
                    var newWidth = Convert.ToInt32(image.Width * ratio);

                    var posX = Convert.ToInt32((width - image.Width * ratio) / 2);
                    var posY = Convert.ToInt32((height - image.Height * ratio) / 2);

                    graphic.Clear(Color.White);
                    graphic.DrawImage(image, posX, posY, newWidth, newHeight);
                    var newFilePath =
                        $"{Path.GetDirectoryName(filePath)}\\{Path.GetFileNameWithoutExtension(filePath)}_{width}x{height}_ratio.png";
                    thumbnail.Save(newFilePath,
                        ImageFormat.Png);
                    Console.WriteLine($"Saving {newFilePath}");
                }
            }
        }
    }
}

 

公众号二维码

关注我的微信公众号
在公众号里留言交流
投稿邮箱:1052839972@qq.com

庭院深深深几许?杨柳堆烟,帘幕无重数。
玉勒雕鞍游冶处,楼高不见章台路。
雨横风狂三月暮。门掩黄昏,无计留春住。
泪眼问花花不语,乱红飞过秋千去。

欧阳修

付款二维码

如果感觉对您有帮助
欢迎向作者提供捐赠
这将是创作的最大动力