我需要将图像(从Web服务获取)转换为base64String,以将它们存储在SQLite数据库中。
编辑:我使用ImageOpened以便在将图像转换为base64String但ImageOpened doest运行之前加载/下载图像。我该如何完成这项任务?我的意思是将图像数组转换为base64。
这是我的代码:
public async void LoadData()
{
//get Json
string str = await Helper.getJSON();
//Deserialize json
MainClass apiData = JsonConvert.DeserializeObject<MainClass>(str);
//the problem loop
for (int i = 0; i < apiData.Categories.Count;i++ )
{
//apiData.Categoriesp[i].icon_image is the url of the image
BitmapImage image = new BitmapImage(new Uri(apiData.Categories[i].icon_image,UriKind.RelativeOrAbsolute));
//it never runs
image.ImageOpened += (s, e) =>
{
//code for conversion of image into memory stream
image.CreateOptions = BitmapCreateOptions.None;
WriteableBitmap wb = new WriteableBitmap(image);
MemoryStream ms = new MemoryStream();
wb.SaveJpeg(ms, image.PixelWidth, image.PixelHeight, 0, 100);
byte[] imageBytes = ms.ToArray();
string base64String = Convert.ToBase64String(imageBytes);
//setting imageInSql property of the list (but it never runs)
apiData.Categories[i].imageInSql = base64String;
};
}
//Inserting into database
using(var db= new SQLiteConnection(App.dbPath)){
//geting null in imageinSql property.
db.InsertAll(apiData.Categories,typeof(Category));
}
}
提前致谢。
答案 0 :(得分:0)
对我来说,它看起来像是在事件处理程序中设置CreateOptions属性。
image.ImageOpened += (s, e) =>
{
//code for conversion of image into memory stream
image.CreateOptions = BitmapCreateOptions.None;
你应该这样做 -
image.CreateOptions = BitmapCreateOptions.None;
image.ImageOpened += (s, e) =>
{
尝试以下代码。
public async void LoadData()
{
//get Json
string str = await Helper.getJSON();
//Deserialize json
MainClass apiData = JsonConvert.DeserializeObject<MainClass>(str);
//the problem loop
for (int i = 0; i < apiData.Categories.Count;i++ )
{
//apiData.Categoriesp[i].icon_image is the url of the image
BitmapImage image = new BitmapImage(new Uri(apiData.Categories[i].icon_image,UriKind.RelativeOrAbsolute));
image.CreateOptions = BitmapCreateOptions.None
//it never runs
image.ImageOpened += (s, e) =>
{
//code for conversion of image into memory stream
WriteableBitmap wb = new WriteableBitmap(image);
MemoryStream ms = new MemoryStream();
wb.SaveJpeg(ms, image.PixelWidth, image.PixelHeight, 0, 100);
byte[] imageBytes = ms.ToArray();
string base64String = Convert.ToBase64String(imageBytes);
//setting imageInSql property of the list (but it never runs)
apiData.Categories[i].imageInSql = base64String;
};
}
//Inserting into database
using(var db= new SQLiteConnection(App.dbPath)){
//geting null in imageinSql property.
db.InsertAll(apiData.Categories,typeof(Category));
}
}