我使用Graphics.DrawImage(DrawText())
将DrawText用于Image。
问题是:我只绘制了三个文本,但原始图像大小为:226kb,当Save()~3.45mb时输出图像。它太大了。
图片尺寸:2732 * 3200
。
我只循环列表textFileSplit
,此列表只有三个项目。
这是我保存图片的全部代码:
foreach (string text in lstTextFromFile)
{
count++;
if (text == "") continue;
Graphics gra = Graphics.FromImage(img);
string st = lstImgAdded.Items[k].Text;
Bitmap bmp = new Bitmap(@"" + st);
bmp = (Bitmap)ResizePanel(bmp, panel2);
panel2.BackgroundImage = bmp;
Graphics gbmp = Graphics.FromImage(bmp);
string[] textFileSplit = text.Split('-');
for (int u = 0; u < textFileSplit.Count(); u++)
{
myColorLabel = activeLabels[u+1].ForeColor;
gbmp.DrawImage(
DrawText(textFileSplit[u], fontType, myColorLabel,
Color.Transparent),
Point.Round(StretchImageSize(new Point(activeLabels[u+1].Location.X, activeLabels[u+1].Location.Y), panel2)));
}
gra.Dispose();
Guid id = Guid.NewGuid();
ScaleImage(bmp, witdhImg, heightImg)
.Save(linkLocation + "\\" + id + "." + imgType,
ImageFormat.Png);
}
在课程ScaleImage()
中,我试图像原始图片一样保留尺寸:
public Image ScaleImage(Image image, int maxWidth, int maxHeight)
{
var ratioX = (double)maxWidth / image.Width;
var ratioY = (double)maxHeight / image.Height;
var ratio = Math.Min(ratioX, ratioY);
var ratio2 = Math.Max(ratioX, ratioY);
var newWidth = (int)(image.Width * ratio);
var newHeight = (int)(image.Height * ratio2);
var newImage = new Bitmap(newWidth, newHeight);
Graphics.FromImage(newImage).DrawImage(image, 0, 0, newWidth, newHeight);
return newImage;
}
答案 0 :(得分:2)
确保在缩放功能中设置分辨率和质量:
public Image ScaleImage(Image image, int maxWidth, int maxHeight)
{
var ratioX = (double)maxWidth / image.Width;
var ratioY = (double)maxHeight / image.Height;
var ratio = Math.Min(ratioX, ratioY);
var ratio2 = Math.Max(ratioX, ratioY);
var newWidth = (int)(image.Width * ratio);
var newHeight = (int)(image.Height * ratio2);
var newImage = var newImage = new Bitmap(newWidth, newHeight, image.PixelFormat);
newImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);
Graphics grPhoto = Graphics.FromImage(newImage);
grPhoto.InterpolationMode = InterpolationMode.High;
grPhoto.DrawImage(image, 0, 0, newWidth, newHeight);
grPhoto.Dispose();
return newImage;
}
以低质量应用EncoderParameters:
ImageCodecInfo pngEncoder = ImageCodecInfo.GetImageDecoders().Where(k=> k.FormatID == ImageFormat.Png.Guid).First();
EncoderParameters encoderParameters;
encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 60L);
ScaleImage(bmp, witdhImg, heightImg)
.Save(linkLocation + "\\" + id + "." + imgType, pngEncoder ,encoderParameters);