我有一个例程,它读取图像,调整其大小并将其放置在新背景上(全新的位图,只是设置了大小)。
这一切都工作得非常完美,但现在我想缩小PNG它输出的文件 - 如果我输出JPEG文件,我得到的文件大小约为我期望的 4K 左右,但我的 PNG 文件大小超过 30K。
我知道我永远无法用 PNG 达到 JPEG 水平,但我想我可以做得更好一点。
当我将输出的 PNG 加载到烟花,我注意到背景和调整大小的图像仍然是单独的层。在 Fireworks 中压平 PNG 可将文件大小减少 5 到 10K。
那么,首先有没有一种方法可以在输出时以编程方式压平 PNG?
其次,还有其他人可以推荐什么来减小 PNG 大小吗?
我使用 PNG 文件,因为我希望将背景保留为透明。
Code:
private static void ResizeImage(String ImageInPath, int MaxWidth, int MaxHeight, String ImageOutPath, Boolean PadImage, Color MyColour)
{
Bitmap MyImage = new Bitmap(ImageInPath);
Bitmap MyResizedImage = null;
int XPosition = 0;
int YPosition = 0;
float Ratio = MyImage.Width / (float)MyImage.Height;
int MyImageHeight = MyImage.Height;
int MyImageWidth = MyImage.Width;
if (MyImage.Width > MyImage.Height)
{
if (MyImage.Width > MaxWidth)
MyResizedImage = new Bitmap(MyImage, new Size(MaxWidth, (int)Math.Round(MaxWidth /
Ratio, 0)));
YPosition = (MaxHeight / 2) - (MyResizedImage.Height / 2);
}
else if (MyImage.Height > MyImage.Width)
{
if (MyImage.Height > MaxHeight)
MyResizedImage = new Bitmap(MyImage, new Size((int)Math.Round(MaxWidth * Ratio,
0), MaxHeight));
XPosition = (MaxWidth / 2) - (MyResizedImage.Width / 2);
}
if (PadImage)
{
Bitmap MyUnderlay = new Bitmap(MaxWidth, MaxHeight);
var Canvas = Graphics.FromImage(MyUnderlay);
Canvas.Clear(MyColour);
Canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
Canvas.DrawImage(MyResizedImage, XPosition, YPosition);
Canvas.Save();
if (MyColour == Color.Transparent)
{
MyUnderlay.Save(ImageOutPath + ".png", ImageFormat.Png);
}
else
{
MyUnderlay.Save(ImageOutPath, ImageFormat.Jpeg);
}
Canvas.Dispose();
MyUnderlay.Dispose();
}
else
{
MyResizedImage.Save(ImageOutPath, ImageFormat.Jpeg);
}
MyResizedImage.Dispose();
MyImage.Dispose();
}