如何在db中存储图像,然后将其显示在图片框中

时间:2015-01-25 12:29:33

标签: c# image byte

在db中存储图像: 我有这个代码,它能够在数据库中存储图像的byte []值, 首先我将图像转换为字节然后将其加载到列表并将其保存在我的数据库中...

private byte[] GetPic(Image img)
{
    using (MemoryStream ms = new MemoryStream())
    {
        Bitmap bmp = new Bitmap(pboxInvent.Image);
        bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
        ms.Position = 0;
        byte[] data = new byte[ms.Length];
        ms.Read(data, 0, data.Length);
        return data.ToArray();
    }
}
public void fillProdList(int catID)
{
    ListCollection.listProduct.Clear();
    ProductInventory pI = new ProductInventory();
    pI.Image = imageToByteArray(pboxInvent.Image);
    ListCollection.listProduct.Add(pI);
}

但我的问题是长度只有13,当我试图拉出图像并将其加载到图片框时,错误说它是内存不足。

这是我将字节转换为图像并将其加载到图片框中:

public Image byteArrayToImage(int prodid)
{
    byte[] imagebyte = dbConnect.retrieveimagefromdb("select imgPhot from prod_Table where prodID=@ID", prodid);
    MemoryStream ms = new MemoryStream(imagebyte);
    ms.Seek(0, SeekOrigin.Begin);
    ms.Write(imagebyte, 0, imagebyte.Length);
    Image image = Image.FromStream(ms); //this line as error as well: parameters invalid
    return image;
} 

public byte[] retrieveimagefromdb(string cmdString, int prodid)
{
    SqlCommand cmd = new SqlCommand(cmdString, SqlConnect);
    cmd.Parameters.Add("@ID", SqlDbType.Int);
    cmd.Parameters["@ID"].Value = prodid;
    SqlConnect.Open();
    byte[] barrImg = (byte[])cmd.ExecuteScalar();
    return barrImg;
}

private void dgvProdList_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
    rbEdit.Enabled = true;
    rbAdd.Checked = false;
    disablingProdTextboxes();
    if(e.RowIndex >= 0)
    {
        DataGridViewRow row = this.dgvProdList.Rows[e.RowIndex];
        byte[] myimage = new byte[0];
        txtProdID.Text = row.Cells["prodID"].Value.ToString().Trim();
        txtProdName.Text = row.Cells["prodName"].Value.ToString().Trim();
        txtModel.Text = row.Cells["prodModel"].Value.ToString().Trim();
        tbSellPrice.Text = String.Format("{0:N2}",row.Cells["sellingPrice"].Value).Trim();
        tbunitPrice.Text = String.Format("{0:N2}", row.Cells["unitPrice"].Value).Trim();
        tbVatper.Text = String.Format("{0:N2}", row.Cells["vatPercentage"].Value).Trim();
        tbmuper.Text = String.Format("{0:N2}", row.Cells["markupPercentage"].Value).Trim();
        txtQty.Text = row.Cells["prodQty"].Value.ToString().Trim();
        txtDesc.Text = row.Cells["prodDesc"].Value.ToString().Trim();
        cbProdCategory.SelectedItem = row.Cells["catName"].Value.ToString().Trim();
        pboxInvent.Image = byteArrayToImage(int.Parse(row.Cells["ProdID"].Value.ToString().Trim()));
    }
}

UPDATE ::

如果我是缓冲区字节数组,使用thsi代码,在哪个区域插入这个,抱歉,我有点在这里。

_sbScript.Append("0x");

for(int i = 0; i< buffer.Length; i ++) {     _sbScript.Append(缓冲液[I]的ToString(" X2",System.Globalization.CultureInfo.InvariantCulture)); }

0 个答案:

没有答案