You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在UWP中如何通过代码向SQL Server插入JPG图片

UWP环境下向SQL Server插入JPG图片的实现方案

核心参数设置

SQL Server通过二进制类型存储图片,因此SqlDbType需设为VarBinary,参数值对应图片的字节数组:

cmd.Parameters.Add("@picture", SqlDbType.VarBinary).Value = imageBytes;

从Image控件获取图片字节数组

需要将Image控件中的图片转换为字节数组,以下是通用异步处理方法:

private async Task<byte[]> GetImageBytesFromImageControl(Image targetImage)
{
    if (targetImage.Source is BitmapImage bitmap)
    {
        // 处理应用内或本地文件Uri的图片
        if (bitmap.UriSource != null && (bitmap.UriSource.Scheme == "ms-appx" || bitmap.UriSource.Scheme == "ms-appdata"))
        {
            StorageFile imageFile = await StorageFile.GetFileFromApplicationUriAsync(bitmap.UriSource);
            using (IRandomAccessStream fileStream = await imageFile.OpenAsync(FileAccessMode.Read))
            using (MemoryStream memoryStream = new MemoryStream())
            {
                await fileStream.AsStreamForRead().CopyToAsync(memoryStream);
                return memoryStream.ToArray();
            }
        }
        // 处理WriteableBitmap类型的图片
        else if (targetImage.Source is WriteableBitmap writeableBitmap)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, ms.AsRandomAccessStream());
                encoder.SetPixelData(
                    BitmapPixelFormat.Bgra8,
                    BitmapAlphaMode.Ignore,
                    (uint)writeableBitmap.PixelWidth,
                    (uint)writeableBitmap.PixelHeight,
                    96, 96,
                    writeableBitmap.PixelBuffer.ToArray()
                );
                await encoder.FlushAsync();
                return ms.ToArray();
            }
        }
    }
    return null;
}

完整插入代码

将上述方法整合到原有代码中,注意方法需标记为async:

conn.Open();

if (conn.State == System.Data.ConnectionState.Open)
{
    using (SqlCommand cmd = conn.CreateCommand())
    {
        // 确保SQL语句格式正确,示例:INSERT INTO Images (Picture) VALUES (@picture)
        cmd.CommandText = SqlString;
        cmd.Parameters.Clear();

        byte[] imageBytes = await GetImageBytesFromImageControl(你的Image控件实例);
        if (imageBytes != null)
        {
            cmd.Parameters.Add("@picture", SqlDbType.VarBinary).Value = imageBytes;
            // 异步执行插入命令
            await cmd.ExecuteNonQueryAsync();
        }
    }
}

额外注意事项

  • SQL Server对应的图片列类型需设置为VarBinary(MAX),避免因图片过大导致存储失败。
  • 如果图片来自文件选择器,可直接读取文件流转换为字节数组,无需经过Image控件,效率更高:
FileOpenPicker picker = new FileOpenPicker();
picker.FileTypeFilter.Add(".jpg");
picker.FileTypeFilter.Add(".jpeg");
StorageFile selectedFile = await picker.PickSingleFileAsync();
if (selectedFile != null)
{
    using (IRandomAccessStream stream = await selectedFile.OpenAsync(FileAccessMode.Read))
    using (MemoryStream ms = new MemoryStream())
    {
        await stream.AsStreamForRead().CopyToAsync(ms);
        byte[] imageBytes = ms.ToArray();
        // 将imageBytes赋值给SQL参数即可
    }
}

内容的提问来源于stack exchange,提问作者Javier Ramos Lopez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 10:32:12