我已经写了一个代码,但是不能正常工作。首先我试图建立一个文件夹并将图像存储在其中,但是由于托管了数据库,因此出现了问题,所以我将图像存储为blob。请帮助我我做错了。谢谢。
public void ItemList_with_images(string value)
{
flowLayoutPanelItemList.Controls.Clear();
// string img_directory = Application.StartupPath + @"\ITEMIMAGE\";
// string[] files = Directory.GetFiles(img_directory, "*.png *.jpg");
try
{
conn.Open();
string sql =
"select distinct Item.Item_id,Item.name,Item.image,Item.cost,Item.price, Category.Name as cat_name from Item" +
" INNER JOIN Category ON Item.Category_id=Category.Category_id" +
" INNER JOIN Ingredients ON Item.Item_id=Ingredients.item_id" +
" INNER JOIN Inventory ON Inventory.Inventory_id = Ingredients.invenotry_id" +
" INNER JOIN inventory_detail ON inventory_detail.inventory_id = Inventory.Inventory_id" +
" where(Item.name like '" + value + "%' and inventory_detail.Quantity > 0 and inventory_detail.loc_id =" + UserInfo.Loc_id + ") " +
"OR (Category.Name like '" + value + "%' and inventory_detail.Quantity > 0 and inventory_detail.loc_id =" + UserInfo.Loc_id + ") ";
dataexe.ExecuteSQL(sql, conn);
DataTable dt = dataexe.GetDataTable(sql, conn);
int currentImage = 0;
for (int i = 0; i < dt.Rows.Count; i++)
{
DataRow dataReader = dt.Rows[i];
Button b = new Button();
//Image i = Image.FromFile(img_directory + dataReader["name"]);
b.Tag = dataReader["Item_id"];
b.Click += new EventHandler(b_Click);
string details = dataReader["Item_id"] +
"\n Name: " + dataReader["name"].ToString() +
"\n Buy price: " + dataReader["cost"].ToString() +
"\n Sell price: " + dataReader["price"].ToString();
b.Name = details;
ImageList il = new ImageList();
il.ColorDepth = ColorDepth.Depth32Bit;
il.TransparentColor = Color.Transparent;
il.ImageSize = new Size(78, 80);
// here i am getting error
il.Images.Add(Image.FromStream(new MemoryStream((byte[]) dataReader["image"])));
// il.Images.Add(Image.FromFile(img_directory + dataReader["image"]));
b.Image = il.Images[0];
b.Margin = new Padding(3, 3, 3, 3);
b.Size = new Size(208, 100);
b.Text.PadRight(4);
b.Text += dataReader["name"].ToString();
b.Text += "\n Price: " + dataReader["price"];
b.Font = new Font("Arial", 9, FontStyle.Bold, GraphicsUnit.Point);
b.TextAlign = ContentAlignment.MiddleLeft;
b.TextImageRelation = TextImageRelation.ImageBeforeText;
flowLayoutPanelItemList.Controls.Add(b);
currentImage++;
}
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
conn.Close();
}
''''
答案 0 :(得分:0)
我不确定您为什么使用ImageList
,如果有 原因,请告诉我。就是说,这是一种非常简短(并经过测试)的方法,该方法从文件加载图像并将其分配给按钮的Image
属性。下面是根据代码使用datareader
的第一种方法的改编。 此方法尚未未通过测试。
public void GetImage()
{
MemoryStream stream = new MemoryStream(File.ReadAllBytes(@"C:\Users\Shai Cohen\Pictures\banana.jpg"));
Image image = Image.FromStream(stream);
button1.Image = image;
}
public void GetImageFromDatareader()
{
MemoryStream stream = new MemoryStream((byte[]) dataReader["image"]));
Image image = Image.FromStream(stream);
button1.Image = image;
}