我正在嘗試輸入流(圖像的zip文件)並提取每個文件。但是我必須在保存之前降低每幅圖像的質量(如果質量爲< 100)。我曾嘗試以下但它從來沒有壓縮形象:在保存前降低圖像/流的質量
public void UnZip(Stream inputStream, string destinationPath, int quality = 80) {
using (var zipStream = new ZipInputStream(inputStream)) {
ZipEntry entry;
while ((entry = zipStream.GetNextEntry()) != null) {
var directoryPath = Path.GetDirectoryName(destinationPath + Path.DirectorySeparatorChar + entry.Name);
var fullPath = directoryPath + Path.DirectorySeparatorChar + Path.GetFileName(entry.Name);
// Create the stream to unzip the file to
using (var stream = new MemoryStream()) {
// Write the zip stream to the stream
if (entry.Size != 0) {
var size = 2048;
var data = new byte[2048];
while (true) {
size = zipStream.Read(data, 0, data.Length);
if (size > 0)
stream.Write(data, 0, size);
else
break;
}
}
// Compress the image and save it to the stream
if (quality < 100)
using (var image = Image.FromStream(stream)) {
var info = ImageCodecInfo.GetImageEncoders();
var @params = new EncoderParameters(1);
@params.Param[0] = new EncoderParameter(Encoder.Quality, quality);
image.Save(stream, info[1], @params);
}
}
// Save the stream to disk
using (var fs = new FileStream(fullPath, FileMode.Create)) {
stream.WriteTo(fs);
}
}
}
}
}
我會很感激,如果有人能告訴我我做錯了什麼。任何關於整理它的建議都會被讚賞,因爲代碼的長大變得醜陋。謝謝
你的問題和你的代碼是矛盾的。 「解壓縮」意味着解壓縮,而你的問題是關於爲什麼不壓縮。你能更清楚地回答你的問題嗎? – 2012-07-17 15:14:43
嗨,彼得,我需要解壓zip文件,然後分別壓縮生成的文件。這可以節省磁盤空間。我認爲斯科特的答案會幫助。 – nfplee 2012-07-17 19:02:05