【问题标题】:The output image after cropping is larger than the original size裁剪后的输出图像大于原始尺寸
【发布时间】:2012-12-31 12:19:15
【问题描述】:

当我使用 Bitmap.Clone() 裁剪图像时,它会创建大于原始图像大小的输出
原始尺寸为:5 M
输出裁剪图像为:28 M

我怎样才能在不损失质量和不大尺寸的情况下进行裁剪? 我的代码是:

private static Image cropImage(Image img, Rectangle cropArea)
{
  var bmpImage = new Bitmap(img);
  Bitmap bmpCrop = bmpImage.Clone(cropArea, bmpImage.PixelFormat);
  img.Dispose();
  bmpCrop.Save(@"D:\Work\CropImage\CropImage\crop.jpg",bmpImage.RawFormat );
  return (Image)(bmpCrop);
}

 static void Main(string[] args)
        {
            string sourceimg = @"D:\Work\Crop Image\CropImage\4032x5808.jpg";
            Image imageoriginal = Image.FromFile(sourceimg);
            int HorX,HorY,VerX,VerY;
            Console.WriteLine("Enter X 1 Cor. ");
            HorX=int.Parse(Console.ReadLine());
            Console.WriteLine("Enter Y 1 Cor. ");
            HorY=int.Parse(Console.ReadLine());
            Console.WriteLine("Enter X 2 Cor. ");
            VerX=int.Parse(Console.ReadLine());
            Console.WriteLine("Enter Y 1 Cor. ");
            VerY= int.Parse(Console.ReadLine());
            Rectangle rect = new Rectangle(HorX,HorY,VerX,VerY);
            cropImage(imageoriginal, rect);
        }

【问题讨论】:

  • 请添加一些代码兵营!
  • 原图是什么格式的?
  • 您在哪里创建Rectangle cropArea?代码是什么?
  • 尝试保存为Jpg而不是RawFormat
  • 您对HorX,HorY,VerX,VerY 的输入是什么 - 请考虑它们的真正含义是X,Y, width from left to right, height from top to bottom?你在第 4 个字符串中也有一点错别字 - 它应该是 ("Enter Y 2 Cor. ");

标签: c# image-processing


【解决方案1】:

您将图像保存为位图,而不是 jpg 或 png,这可能是您的输入格式。更改格式类型,您会看到文件大小直线下降!

此代码示例应该可以帮助您设置质量:-

var qualityEncoder = Encoder.Quality;
var quality = (long)<desired quality>;
var ratio = new EncoderParameter(qualityEncoder, quality );
var codecParams = new EncoderParameters(1);
codecParams.Param[0] = ratio;
var jpegCodecInfo = <one of the codec infos from ImageCodecInfo.GetImageEncoders() with mime type = "image/jpeg">;
bmp.Save(fileName, jpegCodecInfo, codecParams); // Save to JPG

【讨论】:

  • 我尝试将输出另存为 jpg 或 png 和同样的问题
  • 原图格式为“jpg”
  • 感谢罗斯的帮助 :)
【解决方案2】:

通常您无需担心在裁剪时会降低质量,因为您只需以 1:1 的比例保存原始图像的一部分。

您的示例工作正常 - 问题必须在 Rectangle 输入部分。由于您的变量名称令人困惑,我建议您在 MSDN 阅读它。

可以肯定的是,只需使用 new Rectangle(200,100,800,800); 初始化您的矩形(假设您的图像大于 1000x900 )这将从左侧的200th 像素和顶部的100th 像素开始裁剪区域,宽度和高度等于800 像素。

最终质量将保持不变,图像尺寸会更小。

【讨论】:

    猜你喜欢
    • 2021-07-25
    • 1970-01-01
    • 1970-01-01
    • 2023-02-04
    • 2013-04-17
    • 2019-04-10
    • 1970-01-01
    • 1970-01-01
    • 2019-01-11
    相关资源
    最近更新 更多