您的位置:首页 > 其它

对图像进行存储和显示

2005-02-01 23:08 309 查看
以下是在.net中对图像进行存储和显示的方法,其原理是把读入的图像字节数组数据转化为string类型保存在数据库中;在显示时在由字符型转化为字节数组写入页面。

具体方法如下:

一、保存图片

 以二进制流的形式读入图片数据,转化为string保存入数据库

private string GetPhotoID()

{

    string photoid = Guid.NewGuid().ToString();

}

private string GetPhotoType(string photoname)

{

    string type = "";

    int position = photoname.LastIndexOf(".");

    if(position != -1)

        type = photoname.Substring(post+1);

    type = type.ToLower().Trim();

    if(type != "bmp" && type != "jpg" && type != "jpeg" && type != "gif")

        return null;

    return type;

}

private string GetPhotoValue()

{

    int datalength = (int) this.inputfile.PostedFile.InputStream.Length;

    byte[] _data = new BinaryReader(this.inputfile.PostedFile.InputStream).ReadBytes(datalength);

    string photodata = Convert.ToBase64String(_data);

    return photodata;

}

private string SavePhoto()

{

    if(this.inputfile.PostedFile.ContentLength>1024*1024)

        return;

    string photoname = this.inputfile.PostedFile.FileName;

    string photoid = GetPhotoID();

    string phototype = GetPhotoType(photoname)

    if(phototype == null)

        return;

    string photovalue = GetPhotoValue();

    string sqlstring = "Insert Into tablename (columnname...) values('"+photoID+"','"+phototype+"','"+photovalue+"')";

   string connectstr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:/database/....mdb";

   OleDbConnection myconnect = new OleDbConnection(connectstr);

   myconnect.Open();

   OleDbCommand mycommand = new OleDbCommand(sqlstring,myconnect);

   mycommand.ExecuteNonQuery();

   myconnect.Close();

}

二、显示图片

把数据库中的值转化为二进制流输出

private void ShowPhotp()

{

   string type,values;

   int count;

   string connectstr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:/database/....mdb";

   OleDbConnection myconnect = new OleDbConnection(connectstr);

   string sqlstring = "Select columns From tablename where photoID = '"+this.photoID+"' ";

   OleDbDataAdapter myadapter = new OleDbDataAdapter(sqlstring,myconnect);

   DataSet myset = new DataSet();

   myadapter.Fill(myset);

   if(myset.Tables[0].Rows.Count!=0)

   {

    type = myset.Tables[0].Rows[0][1].ToString();

    values = myset.Tables[0].Rows[0][2].ToString();

    count = values.Length;

   }

   else

   {

    return;

   }

   byte[] _bytes = new byte[count];

   _bytes = Convert.FromBase64String(values);

   Response.Clear();

   Response.Buffer = true;

   Response.Charset = "utf-8";

   switch(type)

   {

    case "jpg":

     Response.ContentType = "image/JPEG";

     break;

    case "bmp":

     Response.ContentType = "image/BMP";

     break;

    default:

     return;

   }

   Response.OutputStream.Write(_bytes,0,count);

   Response.End();

}

大家还有什么好的方法一起共享阿!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐