当前位置:编程学习 > C#/ASP.NET >>

如何存储图像格式文件

各位高手:
    VS2005/MySQLServer平台下;存储图像的字段名为Photo,类型为Image,可以为空;一个List页面;一个Add页面,Add页面上有一个HTML的Image控件,一个ASP的FileUpload控件,这个页面是添加和修改共用的页面。
    希望能够实现:
    1.点击添加按钮时进入Add页面,Image控件显示一个默认的图片。
    2.点击List页面上的一条数据的超链接时进入Add页面,Image控件显示该条数据在数据库中的图像,如果为空则显示默认图像。
下面是我的代码,请各位帮帮我。谢谢。
添加时的错误信息:
异常详细信息: System.ArgumentException: 参数无效。
源错误: 
行 159:private static byte[] ResizeImageFile(byte[] imageFile, int targetSize)
行 160:{using (System.Drawing.Image oldImage = System.Drawing.Image.FromStream(new MemoryStream(imageFile)))
行 162: {Size newSize = CalculateDimensions(oldImage.Size, targetSize);

我的代码:

Add.cs页面:
    protected string id = "";
    protected void Page_Load(object sender, EventArgs e)
    {if(!IsPostBack)
        {if(Request.QueryString["id"]!=null)
            {string strId=Request.QueryString["id"].ToString();
             using(SqlConnection conn=new SqlConnection(strConn))
                {using(SqlCommand comm=new SqlCommand("proc_getOneStar",conn))
                    {comm.CommandType=CommandType.StoredProcedure;
                        comm.Parameters.Add("@id",SqlDbType.Int);
                        comm.Parameters["@id"].Value=strId;
                        conn.Open();
                        SqlDataReader dr=comm.ExecuteReader();
                        dr.Read();
                        id = dr[0].ToString();
                        dr.Close();
                        conn.Close();
                     }
                  }
               }
            }
         }
    protected void btnAdd_Click(object sender, EventArgs e)
    {using (SqlConnection conn = new SqlConnection(strConn))
        {using (SqlCommand comm = new SqlCommand("proc_Add", conn))
            {comm.CommandType = CommandType.StoredProcedure;
                comm.Parameters.Add("@Photo", SqlDbType.Image);
                comm.Parameters["@Photo"].Value =
               (FileUpload1.FileBytes != null ? ResizeImageFile(FileUpload1.FileBytes, 150):null);
                conn.Open();
                comm.ExecuteNonQuery();
                conn.Close();
             }
          }
       }
    protected void  btnUpdate_Click(object sender, EventArgs e)
    {using(SqlConnection conn=new SqlConnection(strConn))
        {using(SqlCommand comm=new SqlCommand("proc_UpdateStar",conn))
            {comm.CommandType=CommandType.StoredProcedure;
                comm.Parameters.Add("@id",SqlDbType.Int);
                comm.Parameters.Add("@Photo", SqlDbType.Image);
                comm.Parameters["@id].Value=int.Parse(Request.QueryString["id"].ToString());
                comm.Parameters["@Photo"].Value =
               (FileUpload1.FileBytes != null ? ResizeImageFile(FileUpload1.FileBytes, 150):null);
                conn.Open();
                comm.ExecuteNonQuery();
                conn.Close();
               }
            }
         }
    private static byte[] ResizeImageFile(byte[] imageFile, int targetSize)
    {using (System.Drawing.Image oldImage = System.Drawing.Image.FromStream(new MemoryStream(imageFile)))
        {Size newSize = CalculateDimensions(oldImage.Size, targetSize);
         using (Bitmap newImage = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format24bppRgb))
            {using (Graphics canvas = Graphics.FromImage(newImage))
                {canvas.SmoothingMode = SmoothingMode.AntiAlias;
                 canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
                 canvas.PixelOffsetMode = PixelOffsetMode.HighQuality;
                 canvas.DrawImage(oldImage, new Rectangle(new Point(0, 0), newSize));
                 MemoryStream m = new MemoryStream();
                 newImage.Save(m, ImageFormat.Jpeg);
                 return m.GetBuffer();
                }
            }
        }
    }

    private static Size CalculateDimensions(Size oldSize, int targetSize)
    {Size newSize = new Size();
        if (oldSize.Height > oldSize.Width)
        {newSize.Width = (int)(oldSize.Width * ((float)targetSize / (float)oldSize.Height));
         newSize.Height = targetSize;
        }else
        {newSize.Width = targetSize;
         newSize.Height = (int)(oldSize.Height * ((float)targetSize / (float)oldSize.Width));
        }return newSize;
    }
Add.aspx页面(调用了一个外部类):

<img alt='照片' width="170" src='../../Handler.ashx?id=<%# id %>' height="200" />
<asp:FileUpload ID="FileUpload1" TabIndex="10" runat="server" Width="100%"></asp:FileUpload>

外部类:

<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.IO;
using System.Web;
using System.Data;
using System.Data.SqlClient;


public class Handler : IHttpHandler {

public bool IsReusable {
get {return true;
    }
}
public void ProcessRequest (HttpContext context) {
// 设置响应设置
context.Response.ContentType = "image/jpeg";
context.Response.Cache.SetCacheability(HttpCacheability.Public);
context.Response.BufferOutput = false;
        
Int32 id = -1;
Stream stream = null;
if (context.Request.QueryString["id"] != null && context.Request.QueryString["id"] != "")
                {
id = Convert.ToInt32(context.Request.QueryString["id"]);
                stream = GetPhoto(id);
                }                
    } 
// 从数据库获取照片,如果未返回照片,将获取默认的“placeholder”照片
if (stream == null) stream =GetPhoto();
// 将图像流写入响应流中
const int buffersize = 1024 * 16;
byte[] buffer = new byte[buffersize];
int count = stream.Read(buffer, 0, buffersize);
while (count > 0) {
context.Response.OutputStream.Write(buffer, 0, count);
count = stream.Read(buffer, 0, buffersize);
}
}

    public static Stream GetPhoto(int photoid)
    {
        using (SqlConnection connection = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["isuConnString"].ConnectionString))
        {
            using (SqlCommand command = new SqlCommand("GetPhoto", connection))
            {
                command.CommandType = CommandType.StoredProcedure;
                command.Parameters.Add(new SqlParameter("@id", photoid));
                connection.Open();
                object result = command.ExecuteScalar();
                try
                {
                    return new MemoryStream((byte[])result);
                }
                catch
                {
                    return null;
                }
            }
        }
    }
     public static Stream GetPhoto()
    {string path = HttpContext.Current.Server.MapPath("../pic.jpg");
     return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
    }
}
--------------------编程问答-------------------- 不要把图片放到数据库中吧,放到一个文件夹中,存储路径就可以了,速度还优化些 --------------------编程问答-------------------- 帮顶。 --------------------编程问答-------------------- 问题应该出在这里:{using   (System.Drawing.Image   oldImage   =   System.Drawing.Image.FromStream(new   MemoryStream(imageFile))) 
--------------------编程问答-------------------- 没用过这种方式,都是存路径 --------------------编程问答-------------------- 我一直认为SQLSERVER那个IMAGE没人真存图片,没想到真有人存进去 --------------------编程问答-------------------- 路径存储?不知道。能不能详细说一下啊? --------------------编程问答--------------------
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    //SqlConnection con = new SqlConnection("server=localhost\\SQLEXPRESS;database=market;uid=sa;pwd=");
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        connection conn = new connection();
        SqlConnection con = conn.con1();
        if (FileUpload1.FileName == "" || picAdd())
        {
            string str = "insert into goods (name,price,pic,num,intro,category) values ('" + txtName.Text.Trim() + "','" + txtPrice.Text.Trim() + "','~/image/" + FileUpload1.FileName + "','" + txtNum.Text.Trim() + "','" + txtIntro.Text.Trim() + "','" + DDLcategory.SelectedValue + "')";
            con.Open();
            SqlCommand cmd = new SqlCommand(str, con);
            int i = cmd.ExecuteNonQuery();  
            if (i > 0)
            {
                lbMessage.Text = "商品上传成功!";
                txtName.Focus();
            }
            
        }
        else 
        {            
            Response.Write("<script language=jscript>alert('图片格式不对!');</script>");
        }

    }
    public bool picAdd()
    {
        connection conn = new connection();
        SqlConnection con = conn.con1();   
        if (FileUpload1.HasFile)//如果添加文件存在
        {
            string fileExtension = Path.GetExtension(FileUpload1.FileName).ToLower();//文件扩展名
            string[] arr ={ ".gif", ".bmp", ".jpg", ".jpeg", ".tiff" };
            for (int i = 0; i < arr.Length; i++)
            {
                if (fileExtension == arr[i])
                {
                        string path = Server.MapPath("~/image/");//服务器路径
                        FileUpload1.SaveAs(path + FileUpload1.FileName);//将图片存放于服务器指定位置
                        return true;//以上能完成说明图片上传成功
                }
            }
            return false;
        }
        else
            return false;//没有上传图片
    }

供参考 --------------------编程问答-------------------- 不好意思,把
        connection conn = new connection();
        SqlConnection con = conn.con1(); 

这个去掉,再取消sqlconnection的注释 --------------------编程问答-------------------- 友情UP一下 --------------------编程问答-------------------- 那还有没有其他高手能帮我看下我的这些东西的错误并提供一下解决方案呢? --------------------编程问答-------------------- 不是吧,人呢?都睡觉去了吗? --------------------编程问答-------------------- 存储路径就是说,把你图片的位置放在数据库中,把图片放在服务器的一个文件夹里面,而不是把这个图片放到数据库中,需要显示图片的时候,根据在数据库中存储的他的路径进行显示。 --------------------编程问答-------------------- 请主要参考下影片: 
Image   Save   To   Sql   And   Display.wmv 

另外还可以参考: 
Image   Save   To   Folder   And   Display.wmv 


另外,有位朋友曾问过: 
http://topic.csdn.net/u/20071229/15/503e0dd9-7292-4fdb-925c-01c60bc095c3.html 
是有关图片对齐的.如果对齐,请参考影片: 
http://download.csdn.net/source/321082 


如果都看了影片,还未解决问题,请继续讨论或是在msn   Online讨论。 --------------------编程问答--------------------

string savefile =" ";//路径
FileStream stream = null;
SqlCommand cmd = null;
try
{
stream = new FileStream(savefile, FileMode.Open, FileAccess.Read);
int size = Convert.ToInt32(stream.Length);
Byte[] rtf = new Byte[size];//分配字节数
stream.Read(rtf, 0, size);
cmd = new SqlCommand(sql, sqlCon);
sqlCon.Open();
SqlParameter paramRTF = new SqlParameter(@"@photo",SqlDbType.Image, rtf.Length, ParameterDirection.Input,false, 0, 0, null, DataRowVersion.Current, rtf);
cmd.Parameters.Add(paramRTF);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
    MessageBoxEx.Show("出现未知错误,\n名为:\n" + ex.Message + "错误");
}
finally
{
                    if (stream != null)
                        stream.Close();
                    if (cmd != null)
                        cmd.Parameters.Clear();
                    if (sqlCon != null)
                        sqlCon.Close();
                    FileInfo ff = new FileInfo(savefile);
                    if (ff.Exists)
                        ff.Delete();
}
--------------------编程问答-------------------- 建议楼主  B/S结构不要过量给数据库处理
你可以用GUID来标识上传的文件名 然后放在一个专属文件夹下 ,数据库存文件地址就行了
因为读流的速度很慢 --------------------编程问答-------------------- 好的,谢谢大家,我先一个一个的试~ --------------------编程问答-------------------- http://blog.sina.com.cn/s/blog_3ff6444b010008sx.html这个写的很清楚
--------------------编程问答-------------------- 好了,谢谢大家。有个小问题:
在点击更新按钮的时候它就出现了问题了啊,因为那个FileUpload里面没有内容啊,但是SQL语句里面却需要给它一个值,这个问题怎么解决啊?
1.能不能在加载的时候把这个Image的路径也给绑到FileUpload里而且让它显示出来啊?
2.或者在给Parameters添加值得时候给它把原来的数据库中的数据流赋给它啊?
这2种方法怎么实现呢? --------------------编程问答-------------------- 关注下。
--------------------编程问答-------------------- 大家都说了 UP --------------------编程问答-------------------- 不要把图片放到数据库中吧,放到一个文件夹中,存储路径就可以了,速度还优化些。
========
同意这个方案。
具体的就是:把上传的对象放到一个指定的文件夹中,数据库中只存放路径。
如果把图片等都存入数据库,那么,数据量大的话,那你的数据库压力就会很大了。 --------------------编程问答-------------------- 呵呵,我说了可不算啊,再说如果改动话可能就有点来不及了。


谢谢大家。还有个小问题:

在点击更新按钮的时候它就出现了问题了啊,因为那个FileUpload里面没有内容啊,但是SQL语句里面却需要给它一个值,这个问题怎么解决啊? 

1.能不能在加载的时候把这个Image的路径也给绑到FileUpload里而且让它显示出来啊? 
2.或者在给Parameters添加值得时候给它把原来的数据库中的数据流赋给它啊? 
有没有什么办法实现呢? --------------------编程问答-------------------- UP
补充:.NET技术 ,  ASP.NET
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,