我正在尝试获取输入流(图像的 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);
}
}
}
}
}
如果有人能告诉我我做错了什么,我将不胜感激。由于代码变得有点难看,任何关于整理它的建议都会受到赞赏。谢谢