从文件创建图像并将其保存到SQL时,GDI +存在问题 [英] Problem with GDI+ when creating image from file and saving to SQL

查看:98
本文介绍了从文件创建图像并将其保存到SQL时,GDI +存在问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在尝试将图像保存到SQL数据库,但这给了我错误:GDI +中发生了一般性错误.我的目的是用户使用OpenFileDialog加载图像,并将该图像设置为Image控件.然后,当用户单击更新配置文件"时,图像将保存到"SQL"字段.当我尝试从PC上保存它时,它可以正常运行,但在另一台PC上却不起作用.

首先,当用户使用OpenFileDialog选择图片时,我将路径设置为String变量,称为imagePath.然后,当尝试将图片保存在数据库中时,我使用以下代码:

Hello, I''m trying to save image to SQL database but it gives me the error: A generic error occurred in GDI+. My purpose is that the user loads an image using OpenFileDialog and the image is set to an Image control. Then when the user clicks Update Profile, the image is saved to SQL field. When I try to save it from my PC, it works perfectly, but on the other PC it doesn''t work.

First when the user chooses picture using OpenFileDialog, I set the path to a String variable, called imagePath. Then when trying to save the picture in database I use the following code:

command.CommandText = "update users set avatar = @image where id = '" + user_id + "'"; // The ID of the current logged user

System.Drawing.Image image = System.Drawing.Image.FromFile(imagePath); // Creating            image from the file chosen from OpenFileDialog
MemoryStream ms = new MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] imageBytes = ms.ToArray();
String str = Convert.ToBase64String(imageBytes);   // Converting the byte array to                String
ms.Close();
     command.Parameters.AddWithValue("@image", str);  // Saving the image as string to database



顺便说一句,当我捕获到错误的异常时,它指出函数System.Drawing.Image.FromFile存在错误.

无论如何,我检查了imagePath变量的值,并确保它是正确的.正如我所说,它可以在我的PC上运行,但不能在其他PC上运行.我是否需要向他人发送一些与GDI连接的文件才能正常工作?预先感谢您的帮助!



By the way when I catch the exception of the error, it points that there''s an error with the function System.Drawing.Image.FromFile.

Anyway I checked the value of imagePath variable and I assured it was correct. As I said, it works on my PC, but not on the others. Do I need to send to others some file connected to GDI in order to work properly? Thanks in advance for any help!

推荐答案

不要将其另存为字符串-将其另存为图像类型.这意味着您可以将字节数组直接保存到SQL,而无需将其转换为base64字符串.

顺便说一句,您对正在获取的异常的描述很糟糕(不要对它进行详细说明).说您收到函数错误"并不能告诉我们任何信息.
Don''t save it as a string - save it in the database as an image type. That means you can save the byte array directly to SQL without converting it to a base64 string.

BTW, your description of the exception you''re getting sucks (not to put to fine a point on it). Saying that you get "an error with the function" doesn''t tell us ANYTHING.


这篇关于从文件创建图像并将其保存到SQL时,GDI +存在问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆