Home > other >  .net core: How to convert byte array to image?
.net core: How to convert byte array to image?

Time:12-29

I want to convert byte array to image. I searched a lot of posts in StackOverFlow and found the code below.

public Image ByteArrayToImage(byte[] byteArrayIn)
{
    MemoryStream ms = new MemoryStream(byteArrayIn);
    Image returnImage = Image.FromStream(ms); //  <-- Error here
    return returnImage;
}

But I get an error in Image.FromStream is 'Image' does not contain a definition for 'FromStream' and couldn't find any info on how to fix this.
There is a user who had the same error as me more than 9 years ago but still no answer.
I found a way is:

public Image ByteArrayToImage(byte[] byteArrayIn)
{
    MemoryStream ms = new MemoryStream(byteArrayIn);
    Image returnImage = System.Drawing.Image.FromStream(ms); // <-- Add System.Drawing. here
    return returnImage;
}

And a way:

public Image ByteArrayToImage(byte[] byteArrayIn)
{
    MemoryStream ms = new MemoryStream(byteArrayIn);
    System.Drawing.Image returnImage = System.Drawing.Image.FromStream(ms); // <-- Add System.Drawing. here
    return returnImage;  //  <-- Error here
}

But both ways gives a new error as: Cannot implicitly convert type 'System.Drawing.Image' to 'Repository.Entities.Image'.
This is my Image file in Repository.Entities:

public partial class Image
{
    public int Id { get; set; }
    public int? IdObj { get; set; }
    public string Url { get; set; }
    public sbyte? Thumbnail { get; set; }
    public string Type { get; set; }
}

How to fix it? Looking forward to receiving an answer.

CodePudding user response:

In your ByteArrayToImage function definition you are saying that you will return a class instance of type Repository.Entities.Image but within the function body you are returning a class instance of type System.Drawing.Image.

You can add another property to your Repository.Entities.Image as System.Drawing.Image and set it within the function:

public partial class Image
{
    public int Id { get; set; }
    public int? IdObj { get; set; }
    public string Url { get; set; }
    public sbyte? Thumbnail { get; set; }
    public string Type { get; set; }
    public System.Drawing.Image MyImage{get; set; }
}

public Repository.Entities.Image ByteArrayToImage(byte[] byteArrayIn)
{
    MemoryStream ms = new MemoryStream(byteArrayIn);
    System.Drawing.Image returnImage = System.Drawing.Image.FromStream(ms); 
    return new Repository.Entities.Image {
        MyImage= returnImage
    }
}

Now you can use .MyImage property (which is of type System.Drawing.Image) of your own Image class (which if of type Repository.Entities.Image) in your code.

Additionally, I always prefer to name my classes different than predefined classes (such as Image, Document, Path...etc). If you are planning to have conflicting names, it is a good practice to use full namespaces to prevent confusion of classes.

  • Related