GDI+中发生一般性错误的解决办法

开发的过程中遇到了这个错误想要记录下来!

我是在保存图片文件时遇到的这个错误。

网上也搜了很多资料,试过之后还是会出错,代码其实也都大同小异没有太大区别,先把我遇到问题的经过描述一下:
我要做的是读取身份证信息,其中身份证的证件照也是需要存储下来的,身份证中的照片是二进制流读取的,需要在picturebox控件中展示,我的思路是:

1.读取二进制流,写到内存中

                byte[] imgData = new byte[1111];
                int length = 1111;
                //读取流并填充imgData
                MemoryStream myStream = new MemoryStream();
                for (int i = 0; i < length; i++)
                {
                    myStream.WriteByte(imgData[i]);
                }

2.将二进制流转换为图片并绑定到控件中

                Image myImage = Image.FromStream(myStream);
                picCredentialsPhoto.Image = myImage;

3.生成jpg图片

           _ImgStorePath = AppDomain.CurrentDomain.BaseDirectory + "img\\"+lblFileName.Text + ".jpg;
            //照片另存
            if (!File.Exists(_ImgStorePath))
            {
                File.Create(_ImgStorePath);
            }
            using (Bitmap bmp = new Bitmap(picCredentialsPhoto.Image.Width, picCredentialsPhoto.Image.Height))
            {
                Graphics g = Graphics.FromImage(bmp);//实例一个画板的对象,就用上面的图像的画板
                g.DrawImage(picCredentialsPhoto.Image, 0, 0);//把目标图像画在这个图像文件的画板上
                using (MemoryStream mem = new MemoryStream())
                {
                    bmp.Save(_ImgStorePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
            }

代码执行到bmp.Save(_ImgStorePath, System.Drawing.Imaging.ImageFormat.Jpeg); 时抛出异常“GDI+中发生一般性错误”。

解决办法:
经过调试及多次测试,发现问题在我创建文件那一步,我在创建文件时把图片文件也创建好了,之后再区保存图片的时候就出错了,正确代码如下:

            //区别开始
           _ImgStorePath = AppDomain.CurrentDomain.BaseDirectory + "img\\";
           
            if (!Directory.Exists(_ImgStorePath))
            {
                Directory.CreateDirectory(_ImgStorePath);
            }
            _ImgStorePath += lblVisNumber.Text + ".jpg";
            //区别结束
            using (Bitmap bmp = new Bitmap(picCredentialsPhoto.Image.Width, picCredentialsPhoto.Image.Height))
            {
                Graphics g = Graphics.FromImage(bmp);//实例一个画板的对象,就用上面的图像的画板
                g.DrawImage(picCredentialsPhoto.Image, 0, 0);//把目标图像画在这个图像文件的画板上
                using (MemoryStream mem = new MemoryStream())
                {
                    bmp.Save(_ImgStorePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
            } 

这样就不会报错了

别的同仁有可能是因为其他原因报错的,只是记录一下个人遇到的问题!有需要可借鉴

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值