如何在Windows 8.1应用程序中显示存储在MYSQL中的blob图像

时间:2014-05-22 19:08:58

标签: c# mysql visual-studio-2012 blob

我通常从visual studio windows 8.1项目将图像保存为mysb,但我需要检索此图像并将其放入图像工具中。

下面的代码将图像插入到Mysql中:

public static void insertImage()
{
    FileOpenPicker imagePicker = new FileOpenPicker
    {
        ViewMode = PickerViewMode.Thumbnail,
        SuggestedStartLocation = PickerLocationId.PicturesLibrary,
        FileTypeFilter = { ".jpg", ".jpeg", ".png", ".bmp" }
    };

    StorageFile imageFile = await imagePicker.PickSingleFileAsync();
    string a = imageFile.Name;

    string FileName = a;

    var inputStream = await imageFile.OpenSequentialReadAsync();
    var readStream = inputStream.AsStreamForRead();
    var buffer = new byte[readStream.Length];
    await readStream.ReadAsync(buffer, 0, buffer.Length);
    size = buffer.Length;

    using (MySqlConnection connection = new MySqlConnection(
           "server=localhost;database=familytree;uid=root;"))
    {
        connection.Open();
        MySqlCommand update = new MySqlCommand("UPDATE node SET avatar = '" + 
                     buffer + "' WHERE     email = '" + email + "'", connection);
        update.ExecuteNonQuery();
    }
}

1 个答案:

答案 0 :(得分:0)

存储图片:

private static async Task FileToByteArray(Uri sourceUri) {

var file = await StorageFile.GetFileFromApplicationUriAsync(sourceUri);
using (var inputStream = await file.OpenSequentialReadAsync())
{
    var readStream = inputStream.AsStreamForRead();
    var buffer = new byte[readStream.Length];
    await readStream.ReadAsync(buffer, 0, buffer.Length);
    return buffer;
}

}

并检索它:

private static async Task ConvertToImage(byte [] imageBytes)         {

        var image = new BitmapImage();
        using (var randomAccessStream = new InMemoryRandomAccessStream())
        {
            var dw = new DataWriter(randomAccessStream.GetOutputStreamAt(0));
            dw.WriteBytes(imageBytes);
            await dw.StoreAsync();
            image.SetSourceAsync(randomAccessStream);
        }
        return image;
    }