GDI+加载图片的最佳方法,去除资源锁定

本文介绍了一个在使用 GDI+ 进行图像处理时遇到的“AgenericerroroccurredinGDI+”错误及其解决办法。通过将源图像复制到新的 Bitmap 对象中,可以避免 GDI+ 锁定源文件的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近开发图像识别,当对一个图片进行处理后重新保存的时候,报“A generic error occurred in GDI+”错误,百思不得其解

最后发现原因是:
To retain access to the source bits, GDI+ locks any source file, and forces the application to maintain the life of any source stream, for the life of theBitmap or the Image object.

解决的方法是加载的时候 用Graphics.DrawImage() 来copy Image到一个新建立的Bitmap 对象,然后对这个对像做其它的操作


Source Code

            string fileName = "1.png"; //fileNameCounter.ToString() + ".png";
            string imagePath = @"Sample Images\" + fileName;
            Bitmap b = Bitmap.FromFile(imagePath) as Bitmap;
            this.image = new Bitmap(b.Width, b.Height);
            using (Graphics graph = Graphics.FromImage(this.image))
            {
                graph.DrawImageUnscaled(b, 0, 0);
            }
            b.Dispose();

this.image做为过渡

            string fileName = "1.png"; //fileNameCounter.ToString() + ".png";
            string imagePath = @"Sample Images\" + fileName;                
            this.image.Save(imagePath, ImageFormat.Png);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值