0

抱歉标题不好

我有这个功能:

        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 );
    }

当我的大小为空时,图像加载正常,但是当我在 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;
    }
4

1 回答 1

0

您应该使用另一个 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;

当您将字节写入流时,它会将其当前位置提高写入的字节数(例如参见MemoryStream.Write中的备注)。流对象的后续读取将从相同的位置开始。显然,当您要读取之前写入的字节时,您需要将流倒回到开始写入的位置。

于 2013-03-23T15:01:11.503 回答