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.
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 Image {get; set; }
}
public Image ByteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
System.Drawing.Image returnImage = System.Drawing.Image.FromStream(ms);
return new Repository.Entities.Image {
Image = returnImage
}
}
Now you can use .Image
property of your own Image class Repository.Entities.Image
If I were you, I would name my classes different than predefined classes (such as Image, Document, Path...etc).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.