注意:传入的PNG格式需要长宽相等,size数值可根据原始图片的尺寸进行调整
private static bool ConvertPNGToIcon(string inputPath, string outputPath, int size = 512, bool preserveAspectRatio = true) { using (FileStream inputStream = new FileStream(inputPath, FileMode.Open)) using (FileStream outputStream = new FileStream(outputPath, FileMode.OpenOrCreate)) { return ConvertToIcon(inputStream, outputStream, size, preserveAspectRatio); } } private static bool ConvertToIcon(Stream input, Stream output, int size = 16, bool preserveAspectRatio = false) { Bitmap inputBitmap = (Bitmap)Bitmap.FromStream(input); if (inputBitmap != null) { int width, height; if (preserveAspectRatio) { width = size; height = (inputBitmap.Height + 1) / inputBitmap.Width * size; } else { width = height = size; } Bitmap newBitmap = new Bitmap(inputBitmap, new System.Drawing.Size(width, height)); if (newBitmap != null) { using (MemoryStream memoryStream = new MemoryStream()) { newBitmap.Save(memoryStream, ImageFormat.Png); BinaryWriter iconWriter = new BinaryWriter(output); if (output != null && iconWriter != null) { iconWriter.Write((byte)0); iconWriter.Write((byte)0); iconWriter.Write((short)1); iconWriter.Write((short)1); iconWriter.Write((byte)width); iconWriter.Write((byte)height); iconWriter.Write((byte)0); iconWriter.Write((byte)0); iconWriter.Write((short)0); iconWriter.Write((short)32); iconWriter.Write((int)memoryStream.Length); iconWriter.Write((int)(6 + 16)); iconWriter.Write(memoryStream.ToArray()); iconWriter.Flush(); return true; } } } return false; } return false; }
评论前必须登录!
注册