我使用下面的代码生成带水印的图像,问题是,即使生成的文件的尺寸较小,生成的文件也总是比原始文件大,例如:
original.jpg(1920 * 1440)= 1.11 MB
generated.jpg(960 * 720)= 1.77 MB
我错过了什么吗?
C#:
private void AddWaterMark(string target, string NewName, string newwidth, string newheight)
{
Image imgToResize = Image.FromFile(Path.Combine(target, NewName));
Bitmap indexedImage = new Bitmap(imgToResize, newwidth, newheight);
Graphics g = Graphics.FromImage(indexedImage);
g.DrawImage(indexedImage, new Rectangle(0, 0, newwidth, newheight), 0, 0, indexedImage.Width, indexedImage.Height, GraphicsUnit.Pixel);
g.RotateTransform(-35);
g.DrawString("WWW.example.COM", new Font("Verdana", 24, FontStyle.Bold), new SolidBrush(Color.FromArgb(75, 255, 255, 255)), -100, 350);
imgToResize.Dispose();
indexedImage.Save(target + "\\" + NewName);
indexedImage.Dispose();
g.Dispose();
}
VB:
Private Sub AddWaterMark(target As String, NewName As String, newwidth As String, newheight As String)
Dim imgToResize As Image = Image.FromFile(Path.Combine(target, NewName))
Dim indexedImage As New Bitmap(imgToResize, newwidth, newheight)
Dim g As Graphics = Graphics.FromImage(indexedImage)
g.DrawImage(indexedImage, New Rectangle(0, 0, newwidth, newheight), 0, 0, indexedImage.Width, indexedImage.Height, GraphicsUnit.Pixel)
g.RotateTransform(-35)
g.DrawString("WWW.example.COM", New Font("Verdana", 24, FontStyle.Bold), New SolidBrush(Color.FromArgb(75, 255, 255, 255)), -100, 350)
imgToResize.Dispose()
indexedImage.Save(target + "\" + NewName)
indexedImage.Dispose()
g.Dispose()
End Sub
答案 0 :(得分:3)
您需要指定质量,例如:
var jpgEncoder = GetEncoder(ImageFormat.Jpeg);
var jpgParameters = new EncoderParameters(1);
jpgParameters.Param[0] = new EncoderParameter(Encoder.Quality, 80L);
indexedImage.Save(target + "\\" + NewName, jpgEncoder, jpgParameters);
并使用此方法:
private ImageCodecInfo GetEncoder(ImageFormat format)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
foreach (ImageCodecInfo codec in codecs)
{
if (codec.FormatID == format.Guid)
return codec;
}
return null;
}
答案 1 :(得分:1)
JPEG格式具有品质因数。您可以定义生成的图像将被压缩多少。压缩的越多,您丢失的质量就越高。您可以使用Save
方法设置质量级别。
看看这里的例子: http://msdn.microsoft.com/en-us/library/ytz20d80%28v=vs.110%29.aspx
可在此处找到不同质量等级的样本:http://en.wikipedia.org/wiki/JPEG#Effects_of_JPEG_compression