抱歉标题错误
我有这个功能:
public Stream PictureStream( int size = 0 )
{
if( size == 0 )
{
return new MemoryStream( PictureFile );
}
else
{
ImageFormat format = null;
if( FileFormat == ".jpg" || FileFormat == ".jpeg" )
{
format = ImageFormat.Jpeg;
}
else if( FileFormat == ".png" )
{
format = ImageFormat.Png;
}
else
{
format = ImageFormat.Png;
}
var ms = new MemoryStream( PictureFile );
var returnImage = Image.FromStream( ms );
var img = returnImage.Resize( size );
img.Save( ms , format );
return ms;
}
}
和 ActionResult :
public FileStreamResult Image( long userkey , int? size )
{
var image = UserImagesService.Find( userkey );
image.Size = size == null ? 0 : ( int )size;
return new FileStreamResult( image.Stream , image.ContentType );
}
当我的大小为null时,图像加载正常,但是当我在firefox中传递大小时,我看到了这个错误:
The image “http://localhost:8609/Profiles/Image/4006242570097652224/150” cannot be displayed because it contains errors.
将其保存在磁盘上
我的问题是什么?
更新
我的调整大小功能:
public static Image Resize( this Image imgToResize , int size )
{
int sourceWidth = imgToResize.Width;
int sourceHeight = imgToResize.Height;
float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;
nPercentW = ( ( float )size / ( float )sourceWidth );
nPercentH = ( ( float )size / ( float )sourceHeight );
if( nPercentH < nPercentW )
{
nPercent = nPercentH;
}
else
{
nPercent = nPercentW;
}
int destWidth = ( int )( sourceWidth * nPercent );
int destHeight = ( int )( sourceHeight * nPercent );
Bitmap b = new Bitmap( destWidth , destHeight );
Graphics g = Graphics.FromImage( ( System.Drawing.Image )b );
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage( imgToResize , 0 , 0 , destWidth , destHeight );
g.Dispose();
return ( System.Drawing.Image )b;
}
答案 0 :(得分:1)
您应该使用另一个MemoryStream来保存已调整大小的图像,并在保存图像数据后回退该流:
Image returnImage;
using (var ms = new MemoryStream(PictureFile))
{
returnImage = Image.FromStream(ms);
}
// leaving the using block closes ms
var img = returnImage.Resize(size);
// create new MemoryStream to save the resized image
var resultStream = new MemoryStream();
img.Save(resultStream, format);
// rewind the stream
resultStream.Seek(0, SeekOrigin.Begin);
return resultStream;
当您将字节写入流时,它会将当前Position的字节数增加(请参阅MemoryStream.Write中的备注)。从流对象的后续读取将从相同的位置开始。显然,当您想要读取先前写入的字节时,您需要将流回放到写入开始的位置。