微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用C#如何调整jpeg图像的大小?

使用C#如何调整jpeg图像的大小?代码示例会很棒.

解决方法

public static class ImageHelper
{
    /// <summary>
    /// Resize the image to the specified width and height.
    /// </summary>
    /// <param name="image">The image to resize.</param>
    /// <param name="width">The width to resize to.</param>
    /// <param name="height">The height to resize to.</param>
    /// <returns>The resized image.</returns>
    public static Bitmap ResizeImage(Image image,int width,int height)
    {
        var destRect = new Rectangle(0,width,height);
        var destimage = new Bitmap(width,height);

        destimage.SetResolution(image.HorizontalResolution,image.VerticalResolution);

        using (var graphics = Graphics.FromImage(destimage))
        {
            graphics.CompositingMode = CompositingMode.sourcecopy;
            graphics.CompositingQuality = CompositingQuality.HighQuality;
            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphics.SmoothingMode = SmoothingMode.HighQuality;
            graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

            using (var wrapMode = new ImageAttributes())
            {
                wrapMode.SetWrapMode(WrapMode.TileFlipXY);
                graphics.DrawImage(image,destRect,image.Width,image.Height,GraphicsUnit.Pixel,wrapMode);
            }
        }

        return destimage;
    }

    public static Bitmap ResizeImage(Image image,decimal percentage)
    {
        int width = (int)Math.Round(image.Width * percentage,MidpointRounding.AwayFromZero);
        int height = (int)Math.Round(image.Height * percentage,MidpointRounding.AwayFromZero);
        return ResizeImage(image,height);
    }
}

class Program
{
    static void Main(string[] args)
    {
        string fileName = @"C:\Images\MyImage.jpg";
        FileInfo info = new FileInfo(fileName);
        using (Image image = Image.FromFile(fileName))
        {
            using(Bitmap resizedImage = ImageHelper.ResizeImage(image,0.25m))
            {
                resizedImage.Save(
                    info.DirectoryName + "\\" 
                        + info.Name.Substring(0,info.Name.LastIndexOf(info.Extension)) 
                        + "_" + resizedImage.Width + "_" + resizedImage.Height 
                        + info.Extension,ImageFormat.Jpeg);
            }
        }
    }
}

原文地址:https://www.jb51.cc/csharp/244644.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐