Why this error when doing an image conversion

RogerSchlueter-7899 1,236 Reputation points
2020-04-12T14:11:16.517+00:00

I am trying to convert a BitmapImage to a Byte() with the following code:

Dim ic As New ImageConverter
Dim bts() As Byte = DirectCast(ic.ConvertTo(clsImage, GetType(Byte())), Byte())

The error message I get is:

> Unable to cast object of type 'System.Windows.Media.Imaging.BitmapImage' to type 'System.Drawing.Image'.

The code does NOT attempt to convert the BitmapImage to another image so I don't how to fix this problem.

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,706 questions
0 comments No comments
{count} votes

Accepted answer
  1. Peter Fleischer (former MVP) 19,306 Reputation points
    2020-04-12T20:19:18.127+00:00

    Hi, System.Drawing.ImageConverter converts objects from System.Drawing Namespace. Objects from namespace System.Windows.Media (PresentationCore.dll) like BitmapImage must be converted explicitly. Get byte array you can use this code:

    Dim ms = TryCast(clsImage.StreamSource, MemoryStream)
    Dim bts As Byte() = ms.ToArray
    
    0 comments No comments

0 additional answers

Sort by: Most helpful