上传图片出错的问题

昔梦无痕 2011-03-28 03:15:07
有一下代码:

string imgExt, imgs = "", imgm = "";
System.Drawing.Image oriImg, newImg;
string imageSavePath = Server.MapPath("../UpImage/");
int imageThumbWidth = 0;//小缩略图
int imageThumbHeight = 0;
string imageNewName = DateTime.Now.ToString("yyyyMMddHHmmss");
try
{
if (image.Value != "")
{
HttpPostedFile PostedFile = image.PostedFile;
imgExt = System.IO.Path.GetExtension(PostedFile.FileName).ToString().ToLower();
if (imgExt != ".jpg" && imgExt != ".gif" && imgExt != ".png")
{
MessageBox.Show(this.Page, "上传的文件格式错误");
return;
}
else
{
imageNewName += imgExt;

oriImg = System.Drawing.Image.FromStream(PostedFile.InputStream);
if (oriImg.Width < imageThumbWidth && oriImg.Height < imageThumbWidth)
{
imageThumbHeight = oriImg.Height;
imageThumbWidth = oriImg.Width;
}
else
{
if (oriImg.Width < oriImg.Height)
{
imageThumbHeight = imageThumbWidth;
imageThumbWidth = imageThumbHeight * oriImg.Width / oriImg.Height;
}
else if (oriImg.Width > oriImg.Height)
{
imageThumbHeight = imageThumbWidth * oriImg.Height / oriImg.Width;
}
else imageThumbHeight = imageThumbWidth;
}
newImg = oriImg.GetThumbnailImage(imageThumbWidth, imageThumbHeight, null, new System.IntPtr(0));
imgs = "o_" + imageNewName;
imgm = "t_" + imageNewName;
switch (imgExt)
{
case ".jpg":
oriImg.Save(imageSavePath + imgs, System.Drawing.Imaging.ImageFormat.Jpeg);
newImg.Save(imageSavePath + imgm, System.Drawing.Imaging.ImageFormat.Jpeg);
break;
case ".gif":
oriImg.Save(imageSavePath + imgs, System.Drawing.Imaging.ImageFormat.Gif);
newImg.Save(imageSavePath + imgm, System.Drawing.Imaging.ImageFormat.Gif);
break;
case ".png":
oriImg.Save(imageSavePath + imgs, System.Drawing.Imaging.ImageFormat.Png);
newImg.Save(imageSavePath + imgm, System.Drawing.Imaging.ImageFormat.Png);
break;
}
oriImg.Dispose();
newImg.Dispose();
}
}

执行了出错,ex.Message的报错是:A generic error occurred in GDI+.这是为什么呢?
...全文
176 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
lijing3333 2011-03-29
  • 打赏
  • 举报
回复
如果不是文件夹权限的问题话,就是原来获取的图片对象没有完全释放,再次引用但是图片已经锁定。所以照成冲突。 如果原图跟说缩略图不是一个文件夹的话 就没问题 如果在一个文件夹 想覆盖原文件就会出错。
你参考我的代码 从新创建一个imge对象进行saveas() 你的代码我就不仔细看了。


public void CreateMinImageAndDel(string originalImagePath, string thumbnailPath, int width, int height)
{
Graphics draw = null;
string FileExt = "";

System.Drawing.Image originalImage = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(originalImagePath));

int towidth = width;
int toheight = height;

int ow = originalImage.Width;
int oh = originalImage.Height;

//新建一个bmp图片
System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
System.Drawing.Image bitmap2 = new System.Drawing.Bitmap(towidth, toheight);
//新建一个画板
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);


//设置高质量插值法
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

//设置高质量,低速度呈现平滑程度
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

//清空画布并以透明背景色填充
g.Clear(System.Drawing.Color.Transparent);

//在指定位置并且按指定大小绘制原图片的指定部分
g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight));

try
{
//以jpg格式保存缩略图
FileExt = Path.GetFileNameWithoutExtension(originalImagePath);
          //用新建立的image对象拷贝bitmap对象 让g对象可以释放资源
draw = Graphics.FromImage(bitmap2);
draw.DrawImage(bitmap, 0, 0);

}
catch (System.Exception e)
{
throw e;
}
finally
{
originalImage.Dispose();
bitmap.Dispose();
g.Dispose();
          //保存调整在这里即可
bitmap2.Save(HttpContext.Current.Server.MapPath(thumbnailPath) + FileExt + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
}
}


子夜__ 2011-03-28
  • 打赏
  • 举报
回复
A generic error occurred in GDI+.

这个不好确定 你换个电脑试试下。
二进制图片显示

上传二进制
if (FileUpLogo.HasFile)
{
//取得上传文件的大小
int FileLen = FileUpLogo.PostedFile.ContentLength;
Byte[] FileData = new Byte[FileLen];
//创建访问客户端上传文件的对象
HttpPostedFile hp = FileUpLogo.PostedFile;
//创建数据流对象
System.IO.Stream sr = hp.InputStream;
//将图片数据放到FileData数组对象实例中,0代表数组指针的起始位置,FileLen代表指针的结束位置
sr.Read(FileData, 0, FileLen);
//将FileData 赋值给实体
brandModel.fld_logo = FileData;
}

或者

HttpPostedFile upFile = up_file.PostedFile;//HttpPostedFile对象,用来读取上传图片的属性
fileLength = upFile.ContentLength;//记录文件的长度
try
{
if(fileLength==0)//当文件长度为0的时候
{
txtMessage.Text = "请选择要上传的文件!";
}
else
{
byte[] fileByte = new byte[fileLength];//用图片的长度来初始化一个字节数组存储临时的图片文件
Stream fileStream = upFile.InputStream;//建立文件流对象
fileStream.Read(fileByte,0,fileLength);//读取图片数据到临时存储体fileByte,0为数据指针位置,fileLength为数据长度
string connString = "Data Source=192.168.1.250;database=image;uid=pwqzc;pwd=cn0088";
SqlConnection conn = new SqlConnection(connString);//初始化数据库连接
string insertStr = "insert into image (image_data,image_content_type,image_description,image_size) values (@image_data,@image_content_type,@image_description,@image_size)";
//插入数据库语句
SqlCommand comm = new SqlCommand(insertStr,conn);
comm.Parameters.Add(new SqlParameter("@image_data",SqlDbType.Image));//添加参数
comm.Parameters["@image_data"].Value = fileByte;//给参数赋值
comm.Parameters.Add(new SqlParameter("@image_content_type",SqlDbType.VarChar,50));
comm.Parameters["@image_content_type"].Value = upFile.ContentType;//记录图片类型
comm.Parameters.Add(new SqlParameter("@image_description",SqlDbType.VarChar,50));
comm.Parameters["@image_description"].Value = txtDescription.Text;//把其他的表单数据上传
comm.Parameters.Add(new SqlParameter("@image_size",SqlDbType.Int,4));
comm.Parameters["@image_size"].Value = upFile.ContentLength;//记录图片长度,读取数据的时候使用
conn.Open();//打开数据库连接
comm.ExecuteNonQuery();//添加数据
conn.Close();//关闭数据库
txtMessage.Text = "你已经成功的上传了图片";
}
}
catch(Exception ex)
{
txtMessage.Text = ex.Message.ToString();
}
}
}



读取


using(SqlConnection conn=new SqlConnection())  
{
conn.ConnectionString="";

string strSql="select * from Tb where Id='"+Id+"'";
SqlCommand cmd=new SqlCommand(strSql,conn) ;
conn.Open();
SqlDataReader reader=cmd.ExecuteReader();

if(reader.Read())
{
Response.ContentType = "application/octet-stream";
Response.BinaryWrite((Byte[])reader["Photo"]);
}
Response.End();
conn.Close();
}
haojuntu 2011-03-28
  • 打赏
  • 举报
回复
调试一下,看看具体是什么问题。
KeepMoving 2011-03-28
  • 打赏
  • 举报
回复
加断点,调试吧!
loveheronly 2011-03-28
  • 打赏
  • 举报
回复
protected void btnUpload_Click(object sender, EventArgs e)
{
string type;
if (ddlist.SelectedItem.Value == "")
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('你还没有选择酷信专栏');window.location.href='User.aspx';", true);

return;
}
else
{
type = ddlist.SelectedItem.Value;
ViewState["type"] = type;
ddlist.Enabled = false;
}
Boolean fileOK = true;
if (fUfile.HasFile)
{
if (fileOK)
{
try
{
string Date = System.DateTime.Now.ToString("yyMMddhhmmss");
string subFie = fUfile.FileName.Substring(fUfile.FileName.LastIndexOf("."), 4);
string sLocalPath = "../common/wwjeditor/UploadFiles/";
string folder = Server.MapPath(sLocalPath) + type;

if (!Directory.Exists(folder))
Directory.CreateDirectory(folder);

string path = folder + "\\" + Date + subFie;

string fileName = fUfile.FileName;
int size = fUfile.PostedFile.ContentLength;
// string userName = type;

Multimedia mul = new Multimedia();
mul.Name = fileName;
mul.Size = size;
mul.Path = "common/wwjeditor/UploadFiles/" + type + "/" + Date + subFie;
mul.Series = 1;



//上传到文件夹
sLocalPath = "../common/wwjeditor/UploadFiles/" + type;
path = Server.MapPath(sLocalPath) + "\\" + mul.Path.Substring(mul.Path.LastIndexOf("/") + 1);
if (!File.Exists(path))
{
fUfile.SaveAs(path);
}


if (ViewState["list"] != null)
{
List<Multimedia> list =(List<Multimedia>) ViewState["list"];
mul.Series = list.Count + 1;
list.Add(mul);
gvAccessory.DataSource = list;
gvAccessory.DataBind();
}
else
{
List<Multimedia> list = new List<Multimedia>();
list.Add(mul);
ViewState["list"] = list;
gvAccessory.DataSource = list;
gvAccessory.DataBind();
}

}
catch (System.Exception ex)
{
Response.Write("<script>alert('" + ex.Message + "');</script>");
return;
}
}
}
else
{
Response.Write("<script>alert('上传的文件不符合要求!');</script>");
return;
}

}
MSDNXGH 2011-03-28
  • 打赏
  • 举报
回复
全部打个断点,然后看执行,看看那儿错了,

62,072

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧