我正在尝试将 JPG 图像从 300dpi 重新采样到 150dpi 并返回一个零长度文件。
控制器的 ActionResult:
public ActionResult ViewImage(string file, int dpi = 300, bool log = true)
{
FileExtensions fileExtensions = new FileExtensions();
ImageExtensions imageExtensions = new ImageExtensions();
FileModel fileModel = fileExtensions.GetFileModel(file);
string contentType = fileModel.FileType;
byte[] fileData = fileModel.FileData;
string fileName = Path.GetFileNameWithoutExtension(fileModel.FileName) + "_" + dpi + "DPI" + Path.GetExtension(fileModel.FileName);
FileStreamResult resampledImage = imageExtensions.ResampleImage(fileData, contentType, dpi);
resampledImage.FileDownloadName = fileName;
return resampledImage;
}
重采样图像方法:
public FileStreamResult ResampleImage(byte[] fileData, string contentType, int targetDPI)
{
MemoryStream outputStream = new MemoryStream();
using (Stream sourceStream = new MemoryStream(fileData))
{
Image image = new Image(sourceStream);
image.HorizontalResolution = targetDPI;
image.VerticalResolution = targetDPI;
JpegEncoder jpegEncoder = new JpegEncoder();
jpegEncoder.Quality = 100;
image.Save(outputStream, jpegEncoder);
}
FileStreamResult file = new FileStreamResult(outputStream, contentType);
return file;
}