首页 新闻 会员 周边 捐助

c#内存流输出到文件问题

0
[待解决问题]

using (FileStream fs = System.IO.File.Create(imgSrc))
{
using (Stream stream=CompressImage(imgFile.OpenReadStream()))
{
byte[] srcBuf = StreamToBytes(stream);

                fs.Write(srcBuf, 0, srcBuf.Length);
                fs.Flush();
            }

        }
  //Stream转Byte
  public byte[] StreamToBytes(Stream stream)
    {
        byte[] bytes = new byte[stream.Length];
        stream.Read(bytes, 0, bytes.Length);

        // 设置当前流的位置为流的开始 
        stream.Seek(0, SeekOrigin.Begin);
        return bytes;
    };
    //处理图片
    private Stream CompressImage(Stream stream)
    {
        //Image image = Image.FromStream(stream);
        using (Image image = Image.FromStream(stream))
        {
            Size size = new Size(200, 200);
            int sourceWidth = image.Width;
            //获取图片高度
            int sourceHeight = image.Height;

            float nPercent = 0;
            float nPercentW = 0;
            float nPercentH = 0;
            //计算宽度的缩放比例
            nPercentW = ((float)size.Width / (float)sourceWidth);
            //计算高度的缩放比例
            nPercentH = ((float)size.Height / (float)sourceHeight);

            if (nPercentH < nPercentW)
                nPercent = nPercentH;
            else
                nPercent = nPercentW;
            //期望的宽度
            int destWidth = (int)(sourceWidth * nPercent);
            //期望的高度
            int destHeight = (int)(sourceHeight * nPercent);
            using (Bitmap bitmap = new Bitmap(destWidth, destHeight))
            {

                using (Graphics graphics = Graphics.FromImage(bitmap))
                {
                    graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    //绘制图像
                    graphics.DrawImage(image, 0, 0, destWidth, destHeight);
                    Stream memoryStream = new MemoryStream();
                    image.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                    graphics.Dispose();
                    return memoryStream;
                }
            }
        }
    }

为什么当我不对Stream调用CompressImage方法可以输出到文件,但是调用之后输出的文件就提示格式不正确

灬丶的主页 灬丶 | 初学一级 | 园豆:3
提问于:2019-08-13 16:44
< >
分享
所有回答(1)
0

CompressImage方法返回前,试试重置一下 memoryStream 的Position到头部.
或者StreamToBytes 方法里面读流之前重置一下也可以,就是重复你读流之后的那句代码

shangsharon | 园豆:251 (菜鸟二级) | 2019-08-15 19:13
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册