例如,这里是样本JPEG,我无法保存(!)但可以使用标准的dotnet类读取(例如找出宽度和高度)。原始文件:
http://dl.dropbox.com/u/5079317/184809_1_original.jpg
在Windows图像编辑器中保存相同的图像后,一切都很好: http://dl.dropbox.com/u/5079317/184809_1_resaved.jpg
很久以前我注意到了这个bug,但这不是主要问题。但在目前的项目中,我有成千上万的这样的图像,我真的需要某种解决方案。
可以使用哪些第三方库?
以下是我的阅读方式:
public ImageFile SaveImage(HttpPostedFileBase file, string fileNameWithPath, bool splitImage, out string errorMessage)
{
try
{
using (var stream = file.InputStream)
{
using (Image source = Image.FromStream(stream))
{
return SaveImage(source, fileNameWithPath, splitImage, out errorMessage);
// which actually do source.Save(fileNameWithPath, ImageFormat.Jpeg);
// Exception: A generic error occurred in GDI+.
}
}
}
catch (Exception e)
...
}
答案 0 :(得分:0)
我不确定您使用的是哪个库用于SaveImage,但是如果您只是使用.NET,请在Image对象上调用以下Save方法(带有void返回类型),并返回您需要的任何对象在新文件的System.Drawing.Image对象上。
source.Save(@"C:\{path}\184809_1_resaved.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
没有更多细节,这是我能提供的最好的,因为我不知道ImageFile类的实现是什么样的。 ImageFile是您当前的返回类型,但我只是更改了类型以使其正常工作。
public System.IO.Stream SaveImage(HttpPostedFileBase file, string fileNameWithPath, bool splitImage, out string errorMessage)
{
try
{
using (var stream = file.InputStream)
{
using (System.Drawing.Image source = System.Drawing.Image.FromStream(stream))
{
source.Save(@"C:\resaved.jpg", ImageFormat.Jpeg);
source.Save(stream, ImageFormat.Jpeg);
stream.Position = 0;
errorMessage = string.Empty;
return stream;
}
}
}
catch (Exception e)
{
errorMessage = e.Message.ToString();
}
return null;
}
答案 1 :(得分:0)
Iirc某些格式需要搜索,所有流都不支持。您可以尝试在内存流中缓冲:
using (var input = file.InputStream)
using (var buffer = new MemoryStream())
{
input.CopyTo(buffer);
buffer.Position = 0; // rewind
using (Image source = Image.FromStream(buffer))
{ ... Etc as before ... }
}
答案 2 :(得分:0)
将原始图像调整为相同尺寸可解决问题:
Image img2 = FixedSize(source, source.Width, source.Height, true);
img2.Save(path, ImageFormat.Jpeg);