65.9K
CodeProject 正在变化。 阅读更多。
Home

VB 2008 将 BitmapImage 转换为 System.Byte 的扩展方法

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.67/5 (3投票s)

2009年4月14日

Ms-PL

2分钟阅读

viewsIcon

41479

downloadIcon

351

学习如何在 Visual Basic 2008 中实现一个扩展方法,将 BitmapImage 对象转换为 System.Byte() 数组

引言

Windows Presentation Foundation 提供了一个名为 BitmapImage (命名空间 System.Windows.Media.Imaging)的类,它允许我们在运行时创建和/或加载图像,尽管它针对在 XAML 代码中引用图像进行了优化。

我的需求是将由 BitmapImage 对象表示的图像上传到 SQL Server 数据库,通过基于 ADO.NET Entity Framework 的实体数据模型,该模型接收字节数组形式的图像。

您在互联网上找到的大多数解决方案都与 C# 相关,所以我决定提供一个 Visual Basic 2008 解决方案,提供一个用于 BitmapImage 类的扩展方法,以便我们可以看到 .NET Framework 3.5 的另一个有趣的功能。

Using the Code

首先,让我们从 BitmapImage 类开始。以下代码片段实例化一个并分配一个现有的图像文件,如注释所示(请阅读它们 :-))

'Instantiates an image
Dim photo As New BitmapImage

'Starts the editing and properties assignment phases
photo.BeginInit()

'UriSource establishes the path of the existing file as an URI
photo.UriSource = New Uri("Photo.jpg", UriKind.Relative)

'StreamSource establishes the file’s source as a stream
photo.StreamSource = New IO.FileStream("Photo.jpg", IO.FileMode.Open)

'End of editing
photo.EndInit()

现在我们必须编写一个方法将我们的结果转换为 System.Byte() 类型。 正如我之前提到的,我们不必像以前那样在类中实现自定义方法,而是可以利用 .NET Framework 3.5 引入的另一个有趣的功能:扩展方法。 顾名思义,它们可以成功地用于不同的情况,即使它们主要为这种技术而开发。

您可能还记得,在 Visual Basic 中,自定义扩展方法必须位于一个模块中,该模块必须用 <Extension> 属性装饰,并且必须将要扩展的类型作为参数接收。 根据这个句子,我们可以编写如下内容

Imports System.Runtime.CompilerServices
....
....
<Extension()> Module Module1

   ''' <summary>
   ''' Converts a BitmapImage into a System.Byte() array
   ''' </summary>
   ''' <param name="imageSource"></param>
   ''' <returns></returns>
   ''' <remarks></remarks>
   <Extension()> Function ConvertBitmapImageToBytes_
        (ByVal imageSource As BitmapImage) As Byte()
    'Retrieves as a stream the object assigned as a StreamSource
    'to the BitmapImage
    Dim imageStream As IO.Stream = imageSource.StreamSource

    'Declares an empty bytes array
    Dim buffer As Byte() = Nothing

    'if the stream is not empty..
    If imageStream IsNot Nothing And imageStream.Length > 0 Then

    '..via Using..End Using ensures that access to the resource
    'is just limited to our application
        Using imageReader As New IO.BinaryReader(imageStream) 

    'Retrieves as many bytes as long is the stream
             buffer = imageReader.ReadBytes(Convert.ToInt32(imageStream.Length))
        End Using
    End If

    'returns the new bytes array
    Return buffer
   End Function
End Module

我在代码中编写了特定的注释,以便阅读更加流畅。 使用 XML 注释将使 IntelliSense 能够在您编写代码时显示描述性工具提示。

最后,以下是我们新方法的一个用法示例

Dim MyArray As Byte() = photo.ConvertBitmapImageToBytes

关注点

现在您可以使用 Entity Framework 和 Visual Basic 2008 将图像上传到您的 SQL Server 数据库。

历史

  • 2009 年 4 月 14 日:初始发布
© . All rights reserved.