覆盖现有图像
我有这个代码
private void saveImage()
{
Bitmap bmp1 = new Bitmap(pictureBox.Image);
bmp1.Save("c:\\t.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
// Dispose of the image files.
bmp1.Dispose();
}
,我的驱动器上已经有一个图像 t.jpg "c:\"。
我想每次程序运行时都用新图像替换它。但出现 GDI+ 错误
我该如何解决它?
I have this code
private void saveImage()
{
Bitmap bmp1 = new Bitmap(pictureBox.Image);
bmp1.Save("c:\\t.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
// Dispose of the image files.
bmp1.Dispose();
}
i already have an image t.jpg at my drive "c:\".
i wanted to replace it with a new image every time my program runs. but a GDI+ error shows up
how could i fix it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果图像已存在,则必须删除该图像。
You must remove your image if that is already exists.
我假设您之前使用 Image.Load 方法加载了 c:\t.jpg 图像。如果是这样,则 Image 对象持有图像文件的打开文件句柄,这意味着该文件无法被覆盖。
不要使用 Image.Load 获取原始图像,而是从您创建和处置的 FileStream 加载它。
因此,不要这样做
:
文件句柄已被释放,因此使用 Bitmap.Save 覆盖文件可以成功。因此,您在问题中给出的代码应该有效。保存前无需删除原始文件或处理图像。
额外的:
如果像上面那样关闭 FileStream,则调用 Image.Save 将引发异常。请参阅此处:位图中的 GDI+ 发生一般错误。保存方法
I presume you earlier loaded the c:\t.jpg image using the Image.Load method. If so, the Image object is holding an open file handle on the image file, which means that the file can't be overwritten.
Instead of using Image.Load to get the original image, load it from a FileStream that you create and dispose of.
So, instead of
do this:
The file handle has been released so overwriting the file with Bitmap.Save can succeed. The code you gave in your question should therefore work. There is no need to delete the original file or dispose of the image before saving.
Additional:
If you close the FileStream as above,then calls to Image.Save will throw an exception. See here: A Generic error occurred in GDI+ in Bitmap.Save method