61 lines
2.2 KiB
C#
61 lines
2.2 KiB
C#
|
using System.IO;
|
|||
|
using SixLabors.ImageSharp;
|
|||
|
using SixLabors.ImageSharp.Formats.Png;
|
|||
|
using SixLabors.ImageSharp.Metadata.Profiles.Exif;
|
|||
|
using SixLabors.ImageSharp.Processing;
|
|||
|
using ImageMagick;
|
|||
|
using UnityEngine;
|
|||
|
|
|||
|
namespace HK.FUJIFILM
|
|||
|
{
|
|||
|
public static class PngCompressor
|
|||
|
{
|
|||
|
public static void CompressPng(string inputPath, string outputPath)
|
|||
|
{
|
|||
|
using (Image image = Image.Load(inputPath))
|
|||
|
{
|
|||
|
// 设置 DPI(如果你知道它是 300,可以手动设置)
|
|||
|
image.Metadata.VerticalResolution = 300;
|
|||
|
image.Metadata.HorizontalResolution = 300;
|
|||
|
|
|||
|
// 保存为 PNG,并设置压缩选项
|
|||
|
var encoder = new PngEncoder
|
|||
|
{
|
|||
|
CompressionLevel = PngCompressionLevel.Level9, // 最高压缩,无损
|
|||
|
FilterMethod = PngFilterMethod.Adaptive, // 通常效果最好
|
|||
|
ColorType = PngColorType.Rgb // 保留 RGB,避免 Alpha 影响体积
|
|||
|
};
|
|||
|
|
|||
|
image.Save(outputPath, encoder);
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
/// <summary>
|
|||
|
/// 压缩 PNG 并设置为 300 DPI
|
|||
|
/// </summary>
|
|||
|
/// <param name="inputPath">原始 PNG 路径</param>
|
|||
|
/// <param name="outputPath">压缩后 PNG 输出路径</param>
|
|||
|
public static void CompressPngAndSetDpi(string inputPath, string outputPath)
|
|||
|
{
|
|||
|
using (var image = new MagickImage(inputPath))
|
|||
|
{
|
|||
|
// 设置 300 DPI
|
|||
|
image.Density = new Density(300, 300, DensityUnit.PixelsPerInch);
|
|||
|
|
|||
|
// 设置压缩参数(对于 PNG 有效)
|
|||
|
image.Format = MagickFormat.Png;
|
|||
|
image.Quality = 100; // 保证无损
|
|||
|
image.Depth = 8; // PNG 8bit(通常足够)
|
|||
|
|
|||
|
// 选择压缩过滤器
|
|||
|
image.Settings.SetDefine(MagickFormat.Png, "compression-filter", "5");
|
|||
|
image.Settings.Compression = CompressionMethod.Zip; // PNG 默认
|
|||
|
|
|||
|
// 写入输出文件
|
|||
|
image.Write(outputPath);
|
|||
|
}
|
|||
|
|
|||
|
Debug.Log($"✅ 压缩成功,输出文件: {outputPath}");
|
|||
|
}
|
|||
|
}
|
|||
|
}
|