2012-02-16 4 views
2

자바 스크립트를 사용하여 여러 이미지를 업로드해야합니다. 그래서 나는 이미지 품질을 잃지 않고 이미지를 압축해야합니다.품질이 떨어지는 이미지를 잃지 않고 asp.net으로 이미지를 압축하는 방법

모든 이미지를 phyisical 폴더 "uploads"에 저장해야합니다.

+0

어떤 종류의 이미지? 그들이 jpeg 인 경우 이미 압축되어 있습니다. – Candide

+0

이미지를 업로드하고 있습니다. 일부 JQuery 플러그인을 통해 클라이언트 측의 이미지를 압축 할 수 있다면 더 좋을 것입니다 ... 클라이언트 측 압축 (http://stackoverflow.com/questions/4579193/uploadify-and-image-compression)을 참조하십시오 –

+3

대부분의 이미지 형식은 이미 압축되어 있습니다. 그것들을 더 압축하고 품질을 유지하는 것은 Law & Order 범죄 연구소에서만 가능합니다. –

답변

0

것은 내가 PNG로 이미지를 변환하는 것이 좋습니다 물리적 폴더에 업로드 한 후이 ZIP 압축에 내장 된 사용하는 동안

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

그래서 나는 이미지 품질의 느슨한하지 않고 이미지를 압축 할 필요가있다.

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

또는 당신의 조금 unnoticable 손실이 괜찮다면, 당신은 높은 품질에서 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; 
} 
관련 문제