加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 08:43:43 所属栏目:百科 来源:网络整理
导读:使用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
使用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:ImagesMyImage.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);
            }
        }
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读