Converting An Array of Byte[] To A Bitmap - c#

I have a collection of Bitmaps that are stored in a List<byte[]> object. I want to combine all those Bitmaps into one image (kinda like a paneramic) without converting them back to bitmaps. I've tried using a MemoryStream (see below) but it doesn't seem to work. I always run out of memory or the image comes out corrupted. I would appreciate any thoughts/advice on the matter.
List<byte[]> FrameList = new List<byte[]>();
using (MemoryStream ms = new MemoryStream())
{
for (int i = 0; i < FrameList.Count; i++)
{
//Does not work
ms.Write(FrameList[i], i * FrameList[i].Length, FrameList[i].Length);
//Does not work
ms.Write(FrameList[i], 0, FrameList[i].Length);
}
Bitmap img = (Bitmap)Bitmap.FromStream(ms);
img.Save("D:\\testing.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
}

The steps:
calculate the final image size as sum of size of the individual
images
create a Bitmap with the final size
get the Graphics object
draw all images using the Graphics object
save the final Bitmap
var final = new Bitmap(width, height); // calculated final size
using (var graphics = Graphics.FromImage(final))
{
graphics.DrawImage(...); // draw all partial images onto the final bitmap
}

Related

Image from byte array creating bad image when using Marshalling [duplicate]

I searched all question about byte array but i always failed. I have never coded c# i am new in this side. Could you help me how to make image file from byte array.
Here is my function which stores byte in array named imageData
public void imageReady( byte[] imageData, int fWidth, int fHeight))
You'll need to get those bytes into a MemoryStream:
Bitmap bmp;
using (var ms = new MemoryStream(imageData))
{
bmp = new Bitmap(ms);
}
That uses the Bitmap(Stream stream) constructor overload.
UPDATE: keep in mind that according to the documentation, and the source code I've been reading through, an ArgumentException will be thrown on these conditions:
stream does not contain image data or is null.
-or-
stream contains a PNG image file with a single dimension greater than 65,535 pixels.
Guys thank you for your help. I think all of this answers works. However i think my byte array contains raw bytes. That's why all of those solutions didnt work for my code.
However i found a solution. Maybe this solution helps other coders who have problem like mine.
static byte[] PadLines(byte[] bytes, int rows, int columns) {
int currentStride = columns; // 3
int newStride = columns; // 4
byte[] newBytes = new byte[newStride * rows];
for (int i = 0; i < rows; i++)
Buffer.BlockCopy(bytes, currentStride * i, newBytes, newStride * i, currentStride);
return newBytes;
}
int columns = imageWidth;
int rows = imageHeight;
int stride = columns;
byte[] newbytes = PadLines(imageData, rows, columns);
Bitmap im = new Bitmap(columns, rows, stride,
PixelFormat.Format8bppIndexed,
Marshal.UnsafeAddrOfPinnedArrayElement(newbytes, 0));
im.Save("C:\\Users\\musa\\Documents\\Hobby\\image21.bmp");
This solutions works for 8bit 256 bpp (Format8bppIndexed). If your image has another format you should change PixelFormat .
And there is a problem with colors right now. As soon as i solved this one i will edit my answer for other users.
*PS = I am not sure about stride value but for 8bit it should be equal to columns.
And also this function Works for me.. This function copies 8 bit greyscale image into a 32bit layout.
public void SaveBitmap(string fileName, int width, int height, byte[] imageData)
{
byte[] data = new byte[width * height * 4];
int o = 0;
for (int i = 0; i < width * height; i++)
{
byte value = imageData[i];
data[o++] = value;
data[o++] = value;
data[o++] = value;
data[o++] = 0;
}
unsafe
{
fixed (byte* ptr = data)
{
using (Bitmap image = new Bitmap(width, height, width * 4,
PixelFormat.Format32bppRgb, new IntPtr(ptr)))
{
image.Save(Path.ChangeExtension(fileName, ".jpg"));
}
}
}
}
Can be as easy as:
var ms = new MemoryStream(imageData);
System.Drawing.Image image = Image.FromStream(ms);
image.Save("c:\\image.jpg");
Testing it out:
byte[] imageData;
// Create the byte array.
var originalImage = Image.FromFile(#"C:\original.jpg");
using (var ms = new MemoryStream())
{
originalImage.Save(ms, ImageFormat.Jpeg);
imageData = ms.ToArray();
}
// Convert back to image.
using (var ms = new MemoryStream(imageData))
{
Image image = Image.FromStream(ms);
image.Save(#"C:\newImage.jpg");
}
In addition, you can simply convert byte array to Bitmap.
var bmp = new Bitmap(new MemoryStream(imgByte));
You can also get Bitmap from file Path directly.
Bitmap bmp = new Bitmap(Image.FromFile(filePath));
This was helpful to me: https://www.tek-tips.com/viewthread.cfm?qid=1264492 (Reference answer)
I understand the question as follows:
I have a byte array that contains pixel data e.g. in RGB format (24bit/pixel)
From this raw pixel data I want to create a Bitmap
This code worked for me:
int width = ...;
int height = ...;
byte[] pixelArray = new byte[] {
// Creation of the actual data is not in the scope of this answer
};
Bitmap bmp = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
// Create a BitmapData and lock all pixels to be written
BitmapData bmpData = bmp.LockBits(
new Rectangle(0, 0, bmp.Width, bmp.Height),
ImageLockMode.WriteOnly, bmp.PixelFormat);
// Copy the data from the byte array into BitmapData.Scan0
Marshal.Copy(pixelArray, 0, bmpData.Scan0, pixelArray.Length);
// Unlock the pixels
bmp.UnlockBits(bmpData);
// Do something with your image, e.g. save it to disc
bmp.Save("c:\\temp\\mybmp.bmp", ImageFormat.Bmp);
Based on the accepted answer the OP wanted to interpret imageData byte array as the pixel buffer, rather than an already encoded bitmap stream as the most upvoted answer suggests. And though it works, it contains a lot of copies, as well as palette issues ("And there is a problem with colors right now").
I actually happen to have a drawing library exactly for this purpose (among others). The platform-independent core library allows you to interpret any array of primitive types as a bitmap data:
// Unlike in the accepted answer, no extra buffer allocation or
// array copy happens in the background. Note that we can specify
// a palette for the indexed format so the colors will be interpreted correctly
using var myBitmap = BitmapDataFactory.CreateBitmapData(imageData, new Size(fWidth, fHeight),
stride: fWidth, // stride is same as width because of the 8bpp pixel format
pixelFormat: KnownPixelFormat.Format8bppIndexed,
palette: Palette.Grayscale256());
myBitmap is now an IReadWriteBitmapData instance, allowing a lot of operations (just see the available extension methods). It also offers a pretty fast SetPixel method, which respects the palette so in this particular case it turns any color to grayscale. But if you know the actual pixel format you can also can use the WriteRaw<T> method to access the pixels directly.
And if you use the technology-specific packages such as the one for GDI+ or WPF, then you can simply convert your buffer into known bitmap types such as System.Drawing.Bitmap or System.Windows.Media.WriteableBitmap:
// the accepted answer creates two bitmaps due to the color problems where
// the 2nd one is a 32 bpp image. This solution is much faster, simpler, it avoids
// unnecessary allocations and uses parallel processing internally if possible
var systemBitmap = myBitmap.ToBitmap(); // or ToBitmapAsync, ToWriteableBitmap, etc.

In .Net, while converting "Image" with another image , then one of the image's color quality is affected

In .net application when the image is processed & merged with another image then its colours are affected.
Image image ---------> Uploaded image
Bitmap xy = new Bitmap(image, image.Width, image.Height); -----> Conversion into Bitmap to perform various operations like resize or merge with another image.
So the “image” object has few “PropertyItems” and when we convert image to Bitmap type of object then these “PropertyItems” array is empty, which means these “PropertyItems” were not moved in this conversion.
Now after this image is moved into Bitmap object for merging with another image, then “PropertyItems” array is empty
Due to loss of these propertyitems, color of the image is changed.
For merging, I'm using below code
public string MergeImages(List<BlockPositionDetailsWithSize> blockPositionDetailsWithSize, int layoutWidth, int layoutHeight)
{
var bitmap = new Bitmap(layoutWidth-75, layoutHeight);
float width = 0, height = 0;
using (var g = Graphics.FromImage(bitmap))
{
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.SmoothingMode = SmoothingMode.HighQuality;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.CompositingQuality = CompositingQuality.HighQuality;
var bitmapImg = blockPositionDetailsWithSize.Where(b => b.BlockId.Contains("fImageBlock")).FirstOrDefault();
// This loop is placing two images in graphic object
foreach (var block in blockPositionDetailsWithSize)
{
width = block.Width;
height = block.Height;
g.DrawImage(block.BlockImage, block.PosX, block.PosY, block.Width, block.Height);
}
}
ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg); // change image format
System.IO.MemoryStream ms = new System.IO.MemoryStream();
bitmap.SetResolution(288, 288);
System.Drawing.Imaging.Encoder imgEncoder = System.Drawing.Imaging.Encoder.Quality;
EncoderParameters imgEncoderParameters = new EncoderParameters(1);
EncoderParameter imgEncoderParameter = new EncoderParameter(imgEncoder, 95L); //A quality level of 0 corresponds to the greatest compression, and a quality level of 100 corresponds to the least compression.
imgEncoderParameters.Param[0] = imgEncoderParameter;
bitmap.Save(ms, jpgEncoder, imgEncoderParameters);
byte[] byteImage = ms.ToArray();
string base64String = string.Empty;
base64String = Convert.ToBase64String(byteImage); ////Get Base64
return base64String;
}
Image's color quality can be maintained by following code
foreach (System.Drawing.Imaging.PropertyItem item in bitmapImg.BlockImage.PropertyItems)
{
try
{
bitmap.SetPropertyItem(item);
}
catch
{
}
}
Now the issue is I cannot apply one image's property item on the final image(produced after merging). Because when I apply one image's property items onto another image then the second image's color quality is affected but if I don't apply then the first Image's color quality is affected.
So I am looking for the way to merge two images without loosing of any it's property items.

What byte[] must have in order to be "savable" into bitmap? [duplicate]

I searched all question about byte array but i always failed. I have never coded c# i am new in this side. Could you help me how to make image file from byte array.
Here is my function which stores byte in array named imageData
public void imageReady( byte[] imageData, int fWidth, int fHeight))
You'll need to get those bytes into a MemoryStream:
Bitmap bmp;
using (var ms = new MemoryStream(imageData))
{
bmp = new Bitmap(ms);
}
That uses the Bitmap(Stream stream) constructor overload.
UPDATE: keep in mind that according to the documentation, and the source code I've been reading through, an ArgumentException will be thrown on these conditions:
stream does not contain image data or is null.
-or-
stream contains a PNG image file with a single dimension greater than 65,535 pixels.
Guys thank you for your help. I think all of this answers works. However i think my byte array contains raw bytes. That's why all of those solutions didnt work for my code.
However i found a solution. Maybe this solution helps other coders who have problem like mine.
static byte[] PadLines(byte[] bytes, int rows, int columns) {
int currentStride = columns; // 3
int newStride = columns; // 4
byte[] newBytes = new byte[newStride * rows];
for (int i = 0; i < rows; i++)
Buffer.BlockCopy(bytes, currentStride * i, newBytes, newStride * i, currentStride);
return newBytes;
}
int columns = imageWidth;
int rows = imageHeight;
int stride = columns;
byte[] newbytes = PadLines(imageData, rows, columns);
Bitmap im = new Bitmap(columns, rows, stride,
PixelFormat.Format8bppIndexed,
Marshal.UnsafeAddrOfPinnedArrayElement(newbytes, 0));
im.Save("C:\\Users\\musa\\Documents\\Hobby\\image21.bmp");
This solutions works for 8bit 256 bpp (Format8bppIndexed). If your image has another format you should change PixelFormat .
And there is a problem with colors right now. As soon as i solved this one i will edit my answer for other users.
*PS = I am not sure about stride value but for 8bit it should be equal to columns.
And also this function Works for me.. This function copies 8 bit greyscale image into a 32bit layout.
public void SaveBitmap(string fileName, int width, int height, byte[] imageData)
{
byte[] data = new byte[width * height * 4];
int o = 0;
for (int i = 0; i < width * height; i++)
{
byte value = imageData[i];
data[o++] = value;
data[o++] = value;
data[o++] = value;
data[o++] = 0;
}
unsafe
{
fixed (byte* ptr = data)
{
using (Bitmap image = new Bitmap(width, height, width * 4,
PixelFormat.Format32bppRgb, new IntPtr(ptr)))
{
image.Save(Path.ChangeExtension(fileName, ".jpg"));
}
}
}
}
Can be as easy as:
var ms = new MemoryStream(imageData);
System.Drawing.Image image = Image.FromStream(ms);
image.Save("c:\\image.jpg");
Testing it out:
byte[] imageData;
// Create the byte array.
var originalImage = Image.FromFile(#"C:\original.jpg");
using (var ms = new MemoryStream())
{
originalImage.Save(ms, ImageFormat.Jpeg);
imageData = ms.ToArray();
}
// Convert back to image.
using (var ms = new MemoryStream(imageData))
{
Image image = Image.FromStream(ms);
image.Save(#"C:\newImage.jpg");
}
In addition, you can simply convert byte array to Bitmap.
var bmp = new Bitmap(new MemoryStream(imgByte));
You can also get Bitmap from file Path directly.
Bitmap bmp = new Bitmap(Image.FromFile(filePath));
This was helpful to me: https://www.tek-tips.com/viewthread.cfm?qid=1264492 (Reference answer)
I understand the question as follows:
I have a byte array that contains pixel data e.g. in RGB format (24bit/pixel)
From this raw pixel data I want to create a Bitmap
This code worked for me:
int width = ...;
int height = ...;
byte[] pixelArray = new byte[] {
// Creation of the actual data is not in the scope of this answer
};
Bitmap bmp = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
// Create a BitmapData and lock all pixels to be written
BitmapData bmpData = bmp.LockBits(
new Rectangle(0, 0, bmp.Width, bmp.Height),
ImageLockMode.WriteOnly, bmp.PixelFormat);
// Copy the data from the byte array into BitmapData.Scan0
Marshal.Copy(pixelArray, 0, bmpData.Scan0, pixelArray.Length);
// Unlock the pixels
bmp.UnlockBits(bmpData);
// Do something with your image, e.g. save it to disc
bmp.Save("c:\\temp\\mybmp.bmp", ImageFormat.Bmp);
Based on the accepted answer the OP wanted to interpret imageData byte array as the pixel buffer, rather than an already encoded bitmap stream as the most upvoted answer suggests. And though it works, it contains a lot of copies, as well as palette issues ("And there is a problem with colors right now").
I actually happen to have a drawing library exactly for this purpose (among others). The platform-independent core library allows you to interpret any array of primitive types as a bitmap data:
// Unlike in the accepted answer, no extra buffer allocation or
// array copy happens in the background. Note that we can specify
// a palette for the indexed format so the colors will be interpreted correctly
using var myBitmap = BitmapDataFactory.CreateBitmapData(imageData, new Size(fWidth, fHeight),
stride: fWidth, // stride is same as width because of the 8bpp pixel format
pixelFormat: KnownPixelFormat.Format8bppIndexed,
palette: Palette.Grayscale256());
myBitmap is now an IReadWriteBitmapData instance, allowing a lot of operations (just see the available extension methods). It also offers a pretty fast SetPixel method, which respects the palette so in this particular case it turns any color to grayscale. But if you know the actual pixel format you can also can use the WriteRaw<T> method to access the pixels directly.
And if you use the technology-specific packages such as the one for GDI+ or WPF, then you can simply convert your buffer into known bitmap types such as System.Drawing.Bitmap or System.Windows.Media.WriteableBitmap:
// the accepted answer creates two bitmaps due to the color problems where
// the 2nd one is a 32 bpp image. This solution is much faster, simpler, it avoids
// unnecessary allocations and uses parallel processing internally if possible
var systemBitmap = myBitmap.ToBitmap(); // or ToBitmapAsync, ToWriteableBitmap, etc.

Unable to set a fixed size for image itextsharp

I have been using iTextSharp for creating a report. My report has many images which are of varying sizes. Each image renders in different size eventhough I scale them. I found many solutions but none helped.
My code:
PdfPCell InnerCell;
iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance(Server.MapPath(#"images\Logo.png"));
logo.ScaleToFit(80f, 80f);
InnerCell.FixedHeight = 80f;
InnerCell = new PdfPCell(logo);
I tried adding the image to the chunk but the image positions itself to the top. Since being a dynamic report I can't specify the x and y values in chunk
InnerCell = new PdfPCell(new Phrase(new Chunk(logo, 0, 0)));
I even tried this but I can't get a fixed size.
ScaleToFit(w,h) will scale an image proportionately based on the larger of the width/height of the source image. When scaling multiple images, unless the ratio of the dimensions are all the same you will end up with different sizes. This is by design.
Using ScaleToFit(80,80):
If your source is a square that's 100x100 you'll get a square that's 80x80
If your source is a rectangle that's 200x100 you'll get a rectangle that's 80x40
If your source is a rectangle that's 100x200 you'll get a rectangle that's 40x80
Whatever comes out, measure the width and height and at least one will be one of the dimensions that you specified.
I created a sample program that created random sized images and it gave me the expected output shown in the image (w=80,h=80,h=80,h=80,w=80)
private void test() {
//Output the file to the desktop
var testFile = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test.pdf");
//Standard PDF creation here, nothing special
using (var fs = new FileStream(testFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
using (var doc = new Document()) {
using (var writer = PdfWriter.GetInstance(doc, fs)) {
doc.Open();
//Create a random number generator to create some random dimensions and colors
var r = new Random();
//Placeholders for the loop
int w, h;
Color c;
iTextSharp.text.Image img;
//Create 5 images
for (var i = 0; i < 5; i++) {
//Create some random dimensions
w = r.Next(25, 500);
h = r.Next(25, 500);
//Create a random color
c = Color.FromArgb(r.Next(256), r.Next(256), r.Next(256));
//Create a random image
img = iTextSharp.text.Image.GetInstance(createSampleImage(w, h, c));
//Scale the image
img.ScaleToFit(80f, 80f);
//Add it to our document
doc.Add(img);
}
doc.Close();
}
}
}
}
/// <summary>
/// Create a single solid color image using the supplied dimensions and color
/// </summary>
private static Byte[] createSampleImage(int width, int height, System.Drawing.Color color) {
using (var bmp = new System.Drawing.Bitmap(width, height)) {
using (var g = Graphics.FromImage(bmp)) {
g.Clear(color);
}
using (var ms = new MemoryStream()) {
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
return ms.ToArray();
}
}
}
I think what you're looking for is the ability to scale an image proportionately but also have the image "be that size" which would mean filling in the rest of the pixels with clear or possibly white pixels. See this post for a solution to that.

Byte array to image conversion

I want to convert a byte array to an image.
This is my database code from where I get the byte array:
public void Get_Finger_print()
{
try
{
using (SqlConnection thisConnection = new SqlConnection(#"Data Source=" + System.Environment.MachineName + "\\SQLEXPRESS;Initial Catalog=Image_Scanning;Integrated Security=SSPI "))
{
thisConnection.Open();
string query = "select pic from Image_tbl";// where Name='" + name + "'";
SqlCommand cmd = new SqlCommand(query, thisConnection);
byte[] image =(byte[]) cmd.ExecuteScalar();
Image newImage = byteArrayToImage(image);
Picture.Image = newImage;
//return image;
}
}
catch (Exception) { }
//return null;
}
My conversion code:
public Image byteArrayToImage(byte[] byteArrayIn)
{
try
{
MemoryStream ms = new MemoryStream(byteArrayIn,0,byteArrayIn.Length);
ms.Write(byteArrayIn, 0, byteArrayIn.Length);
returnImage = Image.FromStream(ms,true);//Exception occurs here
}
catch { }
return returnImage;
}
When I reach the line with a comment, the following exception occurs: Parameter is not valid.
How can I fix whatever is causing this exception?
You are writing to your memory stream twice, also you are not disposing the stream after use.
You are also asking the image decoder to apply embedded color correction.
Try this instead:
using (var ms = new MemoryStream(byteArrayIn))
{
return Image.FromStream(ms);
}
Maybe I'm missing something, but for me this one-liner works fine with a byte array that contains an image of a JPEG file.
Image x = (Bitmap)((new ImageConverter()).ConvertFrom(jpegByteArray));
EDIT:
See here for an updated version of this answer: How to convert image in byte array
public Image byteArrayToImage(byte[] bytesArr)
{
using (MemoryStream memstr = new MemoryStream(bytesArr))
{
Image img = Image.FromStream(memstr);
return img;
}
}
I'd like to note there is a bug in solution provided by #isaias-b.
That solution assume that stride is equal to row length. But it is not always true. Due to memory alignments performed by GDI, stride can be greater then row length. This must be taken into account. Otherwise invalid shifted image will be generated. Padding bytes in each row will be ignored.
The stride is the width of a single row of pixels (a scan line), rounded up to a four-byte boundary.
Fixed code:
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
public static class ImageExtensions
{
public static Image ImageFromRawBgraArray(this byte[] arr, int width, int height, PixelFormat pixelFormat)
{
var output = new Bitmap(width, height, pixelFormat);
var rect = new Rectangle(0, 0, width, height);
var bmpData = output.LockBits(rect, ImageLockMode.ReadWrite, output.PixelFormat);
// Row-by-row copy
var arrRowLength = width * Image.GetPixelFormatSize(output.PixelFormat) / 8;
var ptr = bmpData.Scan0;
for (var i = 0; i < height; i++)
{
Marshal.Copy(arr, i * arrRowLength, ptr, arrRowLength);
ptr += bmpData.Stride;
}
output.UnlockBits(bmpData);
return output;
}
}
To illustrate what it can lead to, let's generate PixelFormat.Format24bppRgb gradient image 101x101:
var width = 101;
var height = 101;
var gradient = new byte[width * height * 3 /* bytes per pixel */];
for (int i = 0, pixel = 0; i < gradient.Length; i++, pixel = i / 3)
{
var x = pixel % height;
var y = (pixel - x) / width;
gradient[i] = (byte)((x / (double)(width - 1) + y / (double)(height - 1)) / 2d * 255);
}
If we will copy entire array as-is to address pointed by bmpData.Scan0, we will get following image. Image shifting because part of image was written to padding bytes, that was ignored. Also that is why last row is incomplete:
But if we will copy row-by-row shifting destination pointer by bmpData.Stride value, valid imaged will be generated:
Stride also can be negative:
If the stride is positive, the bitmap is top-down. If the stride is negative, the bitmap is bottom-up.
But I didn't worked with such images and this is beyond my note.
Related answer: C# - RGB Buffer from Bitmap different from C++
All presented answers assume that the byte array contains data in a known file format representation, like: gif, png or jpg. But i recently had a problem trying to convert byte[]s, containing linearized BGRA information, efficiently into Image objects. The following code solves it using a Bitmap object.
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
public static class Extensions
{
public static Image ImageFromRawBgraArray(
this byte[] arr, int width, int height)
{
var output = new Bitmap(width, height);
var rect = new Rectangle(0, 0, width, height);
var bmpData = output.LockBits(rect,
ImageLockMode.ReadWrite, output.PixelFormat);
var ptr = bmpData.Scan0;
Marshal.Copy(arr, 0, ptr, arr.Length);
output.UnlockBits(bmpData);
return output;
}
}
This is a slightly variation of a solution which was posted on this site.
In one line:
Image.FromStream(new MemoryStream(byteArrayIn));
try (UPDATE)
MemoryStream ms = new MemoryStream(byteArrayIn,0,byteArrayIn.Length);
ms.Position = 0; // this is important
returnImage = Image.FromStream(ms,true);
there is a simple approach as below, you can use FromStream method of an image to do the trick,
Just remember to use System.Drawing;
// using image object not file
public byte[] imageToByteArray(Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
One liner:
Image bmp = (Bitmap)((new ImageConverter()).ConvertFrom(imageBytes));
You haven't declared returnImage as any kind of variable :)
This should help:
public Image byteArrayToImage(byte[] byteArrayIn)
{
try
{
MemoryStream ms = new MemoryStream(byteArrayIn,0,byteArrayIn.Length);
ms.Write(byteArrayIn, 0, byteArrayIn.Length);
Image returnImage = Image.FromStream(ms,true);
}
catch { }
return returnImage;
}
This is inspired by Holstebroe's answer, plus comments here: Getting an Image object from a byte array
Bitmap newBitmap;
using (MemoryStream memoryStream = new MemoryStream(byteArrayIn))
using (Image newImage = Image.FromStream(memoryStream))
newBitmap = new Bitmap(newImage);
return newBitmap;
Most of the time when this happens it is bad data in the SQL column. This is the proper way to insert into an image column:
INSERT INTO [TableX] (ImgColumn) VALUES (
(SELECT * FROM OPENROWSET(BULK N'C:\....\Picture 010.png', SINGLE_BLOB) as tempimg))
Most people do it incorrectly this way:
INSERT INTO [TableX] (ImgColumn) VALUES ('C:\....\Picture 010.png'))
First Install This Package:
Install-Package SixLabors.ImageSharp -Version 1.0.0-beta0007
[SixLabors.ImageSharp][1]
[1]: https://www.nuget.org/packages/SixLabors.ImageSharp
Then use Below Code For Cast Byte Array To Image :
Image<Rgba32> image = Image.Load(byteArray);
For Get ImageFormat Use Below Code:
IImageFormat format = Image.DetectFormat(byteArray);
For Mutate Image Use Below Code:
image.Mutate(x => x.Resize(new Size(1280, 960)));
I suggest using ImageSharp
Image<Bgra32> image = SixLabors.ImageSharp.Image.LoadPixelData<Bgra32>
(byteArray
, pageWidth
, pageHeight);

Categories

Resources