ITPub博客

首页 > 应用开发 > > c#内存流输出到文件问题

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

作者:cartoonfish 时间:2019-09-18 10:01:46 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方法可以输出到文件,但是调用之后输出的文件就提示格式不正确

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/1409/viewspace-3121449/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: plotly python怎么用
下一篇: subimt提交按钮
请登录后发表评论 登录
全部评论

注册时间:2019-04-15

  • 博文量
    96
  • 访问量
    514