簡體   English   中英

如何使用asp.net壓縮圖像而又不損失圖像質量

[英]how to compress images with asp.net with out lose of qualityof image

我必須使用Java腳本上傳多個圖像。 因此,我需要壓縮那些圖像而不會降低圖像質量。

我必須將所有圖像存儲在物理文件夾“上載”中。

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));
    }
}

所以在物理文件夾中上傳時,我需要壓縮圖像而不會降低圖像質量

我建議將圖像轉換為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,然后再將其ZIP壓縮。 在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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM