如何使用asp.net压缩图像而不丢失图像质量

时间:2012-02-16 11:31:32

标签: c#

我必须使用java-script上传多个图像。所以我需要压缩这些图像而不会丢失图像质量。

我必须将所有图像存储在phyisical文件夹“uploads”中。

HttpFileCollection hfc = Request.Files;
for (int i = 0; i < hfc.Count; i++) {
    HttpPostedFile hpf = hfc[i];
    if (hpf.ContentLength > 0) {
        hpf.SaveAs(Server.MapPath("~/uploads/") +System.IO.Path.GetFileName(hpf.FileName));
    }
}

因此我需要在物理文件夹中上传时压缩图像而不会丢失图像质量

1 个答案:

答案 0 :(得分:0)

我建议将图像转换为PNG,然后使用内置的ZIP压缩。

public static void SaveToPNG(Bitmap SourceImage, string DestinationPath)
{
    SourceImage.Save(DestinationPath, ImageFormat.Png);
    CompressFile(DestinationPath, true);
}

private static string CompressFile(string SourceFile, bool DeleteSourceFile)
{
    string TargetZipFileName = Path.ChangeExtension(SourceFile, ".zip");

    using (ZipArchive archive = ZipFile.Open(TargetZipFileName, ZipArchiveMode.Create))
    {
        archive.CreateEntryFromFile(SourceFile, Path.GetFileName(SourceFile),CompressionLevel.Optimal);
    }

    if(DeleteSourceFile == true)
    {
        File.Delete(SourceFile);
    }
    return TargetZipFileName;
}

或者如果您不介意有点不可忽视的损失,那么您可以转换为高质量的JPG,然后将其压缩。 100%的质量,您的用户可能不会注意到任何差异,您的质量越低,图像越小,但这会使您的“质量不受损失”失败。

private static ImageCodecInfo __JPEGCodecInfo = null;
private static ImageCodecInfo _JPEGCodecInfo
{
    get
    {
        if (__JPEGCodecInfo == null)
        {
            __JPEGCodecInfo = ImageCodecInfo.GetImageEncoders().ToList().Find(delegate (ImageCodecInfo codec) { return codec.FormatID == ImageFormat.Jpeg.Guid; });
        }
        return __JPEGCodecInfo;
    }
}
public static void SaveToJPEG(Bitmap SourceImage, string DestinationPath, long Quality)
{
    EncoderParameters parameters = new EncoderParameters(1);

    parameters.Param[0] = new EncoderParameter(Encoder.Quality, Quality);

    SourceImage.Save(DestinationPath, _JPEGCodecInfo, parameters);

    CompressFile(DestinationPath, true);
}

private static string CompressFile(string SourceFile, bool DeleteSourceFile)
{
    string TargetZipFileName = Path.ChangeExtension(SourceFile, ".zip");

    using (ZipArchive archive = ZipFile.Open(TargetZipFileName, ZipArchiveMode.Create))
    {
        archive.CreateEntryFromFile(SourceFile, Path.GetFileName(SourceFile),CompressionLevel.Optimal);
    }

    if(DeleteSourceFile == true)
    {
        File.Delete(SourceFile);
    }
    return TargetZipFileName;
}