Error" Parameter is not valid " while converting Bytes into Image - c#

I am converting bytes into an image but I get an error
Parameter is not valid
I am pasting my code. Kindly check the code and suggested that was I am doing right or wrong.
Image arr1 = byteArrayToImage(Bytess);
This is the function.
public static Image byteArrayToImage(byte[] byteArrayIn)
{
if (null == byteArrayIn || byteArrayIn.Length == 0)
return null;
MemoryStream ms = new MemoryStream(byteArrayIn);
try
{
Process currentProcess1 = Process.GetCurrentProcess();
Image returnImage = Image.FromStream(ms);
return returnImage;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I applied many techniques and solutions but it did not work for me
Your answer would be appreciated.
Thanks

try this
public Image byteArrayToImage(byte[] byteArrayIn)
{
System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter();
Image img = (Image)converter.ConvertFrom(byteArrayIn);
return img;
}

After trying many things I found a way which has a little bit more control.
In this example you can specify the pixel format and copy the bytes to a Bitmap.
byte[] buffer = GetImageBytes();
var bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
var bitmap_data = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
Marshal.Copy(buffer, 0, bitmap_data.Scan0, buffer.Length);
bitmap.UnlockBits(bitmap_data);
var result = bitmap as Image;

The problem is because, you are bringing it incorrectly from database. Try changing your code like this:
while (registry.Read())
{
byte[] image = (byte[])registry["Image"];
}

In my case I got the error since my base64 string had wrong encoding before calling Image.FromStream.
This worked for me in the end:
byte[] bytes = System.Convert.FromBase64String(base64ImageString);
using (MemoryStream ms = new MemoryStream(bytes))
{
var image = Image.FromStream(ms);
image.Save(filePath, System.Drawing.Imaging.ImageFormat.Png);
}

cmd.CommandText="SELECT * FROM `form_backimg` WHERE ACTIVE=1";
MySqlDataReader reader6= cmd.ExecuteReader();
if(reader6.Read())
{
code4 = (byte[])reader6["BACK_IMG"]; //BLOB FIELD NAME BACK_IMG
}
reader6.Close();
MemoryStream stream = new MemoryStream(code4); //code4 is a public byte[] defined on top
pictureBox3.Image = Image.FromStream(stream);

try this,
public Image byteArrayToImage(byte[] byteArrayIn)
{
Image returnImage = null;
using (MemoryStream ms = new MemoryStream(byteArrayIn))
{
returnImage = Image.FromStream(ms);
}
return returnImage;
}

Related

How to convert base64 string to BitmapImage?

I'm reading data from a blob in MySQL in Base64 String.
I want to convert this to a BitmapImage.
I've tried many ways, but without success.
Here is an example:
public static BitmapImage Base64ToBitmapImage(this string base64String)
{
byte[] binaryData = Convert.FromBase64String(base64String);
BitmapImage img = new BitmapImage();
img.BeginInit();
img.StreamSource = new MemoryStream(binaryData);
img.EndInit();
return img;
}
One example of blob:
iVBORw0KGgoAAAANSUhEUgAAAIwAAACMCAIAAAAhotZpAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAACk0SURBVHhe7d1rjKVVuSfwql33a1d3V99o+gJNA7bQNAgeETRxJIQELxgTvOFBHUcP5ggzx8QMyXwymox+GIzhgxJzzHxgxKiYyQzjdRAvnAENGkAEmu4G+lZ9q66u+65dVbvmt95n1+vuG3ZXV3tq96l/Ksv1rvWstZ7n+a/nWevdezfWz8zM1C1iYaNQ+d9FLGAsklQDWCSpBrBIUg1gkaQawCJJNYBFkmoAiyTVABZJqgEsklQDWCSpBrBIUg1gkaQawCJJNYBFkmoAC5Sk6enpcrlceairy7/0OuHbrzP5MowMmC1Qaa0pLOgv/cK/USkUCvX19dGeU6ilsbExGkMSQix/hHxgjWLBkYSAaj5yTE1N5XxgiNoNDQ3xeEqQiUlqnSH4VyPpdOuWSiXeDwJCBmdZz79dLDiSIN/7kdZAvaWlRWVyclKvkMKcXuGlXa/ZAnoD2QR/ga4oa5HyfzWSwvUnQyQpuTKYiEYYHBzUFax0d3fnqQ+YEHTiRghWj8qtyyuLJJ0FTkfSvn37qMSVbW1tnZ2dzc3NJHGzd+9epS4kaW9vb8eTx2KxGCGljiG90NTUpNFsEVU5Yomaw4Ij6cUXX5TT9PI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5ctTEqE0ZpTlQFlzG5ysLEgo4kvgMkcWW+9x0t8S+5vQnJbzt27HjkkUd+8IMfuGQjLwZeffXVziHvpzfffLOrebyB4kYaZK+jK156crYWSTrvYELQqc7XwWU8noyFTMbpUHsa/xvEhUOS6IHKw4WFCyTdBdSDKojHk6GrUqsdXCAkVWqzWCRpEX9r1PyZdMpNdoHtvMXbXQ1gMd3VABYjqQawSFINYJGkGsAiSTWARZJqAIsk1QAWSaoBLJJUA1gkqQawSFINYJGkGsAiSTWARZJqAIsk1QAWSaoBLJJUA1gkqQawSFINYJGkBY+6uv8PydCKtZTj+VcAAAAASUVORK5CYII=
In my project, I used this method to convert an array of bytes to BitmapImage:
public static BitmapImage? ConvertToBitmapImage(byte[]? imageData)
{
if (imageData == null || imageData.Length == 0) return null;
var image = new BitmapImage();
using (var mem = new MemoryStream(imageData))
{
mem.Position = 0;
image.BeginInit();
image.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
image.CacheOption = BitmapCacheOption.OnLoad;
image.UriSource = null;
image.StreamSource = mem;
image.EndInit();
}
image.Freeze();
return image;
}
You can use this function by passing an array of bytes to it:
public static BitmapImage? Base64ToBitmapImage(this string base64String)
{
byte[] binaryData = Convert.FromBase64String(base64String);
return ConvertToBitmapImage(binaryData);
}
you can use this functions.
private string ImageToBase64String(string file)
{
Bitmap bitmap = new Bitmap(file);
MemoryStream ms = new MemoryStream();
bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] arr = new byte[ms.Length];
ms.Position = 0;
ms.Read(arr, 0, (int)ms.Length);
ms.Close();
string strBase64 = Convert.ToBase64String(arr);
return strBase64;
}
private Bitmap Base64StringToImage(string base64)
{
byte[] arr = Convert.FromBase64String(base64);
MemoryStream ms = new MemoryStream(arr);
Bitmap bitmap = new Bitmap(ms);
return bitmap;
}
The code above works fine. The cause of the problem its on MySQL return.
The value from a blob column returns returns as a byte on C# MySQL Lybrary.
And I was converting it to a Base64 String and recoverting to a byte.
I excluded this confusion in my code and problem fixed.

Convert WriteableBitmap to VideoFrame - A generic error occurred in GDI+

So i try to use ONNX file for local object detection, work great in UWP and WPF with local saved image.
Now, the problem is, to use my detection algorithm with 3D live camera.
My detection algorithm expect a (Windows.Media.)VideoFrame, and my camera give me an (System.Windows.Media.Imaging.)WriteableBitmap.
So here what i have donne already :
Convert my WriteableBitmap to Bitmap :
private System.Drawing.Bitmap BitmapFromWriteableBitmap(System.Windows.Media.Imaging.WriteableBitmap writeBmp)
{
System.Drawing.Bitmap bmp;
using (MemoryStream outStream = new MemoryStream())
{
System.Windows.Media.Imaging.BitmapEncoder enc = new BmpBitmapEncoder();
enc.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create((System.Windows.Media.Imaging.BitmapSource)writeBmp));
enc.Save(outStream);
bmp = new System.Drawing.Bitmap(outStream);
}
return bmp;
}
Now i want to tranform my Bitmap to SoftwareBitmap (for creating a VideoFrame with VideoFrame.CreateWithSoftwareBitmap)
Windows.Storage.Streams.InMemoryRandomAccessStream stream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
Stream strm;
private async Task<SoftwareBitmap> SoftWareBitmapFromBitmap(Bitmap bitmap)
{
SoftwareBitmap softwareBitmap2;
strm = stream.AsStream();
bitmap.Save(strm, ImageFormat.Png);
Windows.Graphics.Imaging.BitmapDecoder decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(stream);
softwareBitmap2 = await decoder.GetSoftwareBitmapAsync();
return softwareBitmap2;
}
But in this last function i got an error in :
bitmap.Save(strm, ImageFormat.Bmp);
I got the "A generic error occurred in GDI+."
I have try to lock/unlock the bitmap, i have try different ImageFormat, if i change to 'ImageFormat.MemoryBmp' i got an "Value cannot be null".
Thank you.
I dont know how to quotes or thumb up answer and sorry for that.
That work great just with : outStream.AsRandomAccessStream()
Here the final function :
public async Task<System.Windows.Shapes.Rectangle> GetPositionDetection(WriteableBitmap wrtBitmap, double imageWidth, double imageHeight)
{
try
{
MemoryStream outStream = new MemoryStream();
System.Windows.Media.Imaging.BitmapEncoder enc = new BmpBitmapEncoder();
enc.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create((System.Windows.Media.Imaging.BitmapSource)wrtBitmap));
enc.Save(outStream);
Windows.Storage.Streams.InMemoryRandomAccessStream stream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
Windows.Graphics.Imaging.BitmapDecoder decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(outStream.AsRandomAccessStream());
SoftwareBitmap tmp2 = await decoder.GetSoftwareBitmapAsync();
VideoFrame inputImage = VideoFrame.CreateWithSoftwareBitmap(tmp2);
IList<PredictionModel> ResultsList = await objDetec.PredictImageAsync(inputImage);
if (ResultsList.Count == 0)
{
Console.WriteLine("Object not detected");
return null;
}
else
{
var itm = ResultsList.First(x => x.Probability == ResultsList.Max(y => y.Probability));
System.Windows.Shapes.Rectangle rct = new System.Windows.Shapes.Rectangle();
rct.Stroke = System.Windows.Media.Brushes.Red;// new SolidColorBrush(Windows.UI.Colors.Red);
rct.StrokeThickness = 2;
rct.Width = imageWidth * (MappingEchellefloat(0, 1, 0, 100, itm.BoundingBox.Width) / 100);
rct.Height = imageHeight * (MappingEchellefloat(0, 1, 0, 100, itm.BoundingBox.Height) / 100);
Console.WriteLine("Object returned : " + ResultsList.Count);
return rct;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return null;
}
}
Thank you for your help.

Bitmap from Memstream of an SVG gives invalid parameter exception

The last line of the following code gives the error "Parameter is not valid", when the original image is an SVG:
var imageBytes = Convert.FromBase64String(imageBase64String);
var memStream = new MemoryStream(imageBytes);
//memStream.Seek(0, SeekOrigin.Begin);
var imageObject = new Bitmap(memStream);
Help please. Thanks.
EDIT: The image for example I am using is the image of the first formula in the following page right under the Theoremsection:
https://en.wikipedia.org/wiki/Green%27s_theorem
Can you try with 'using' for memorystream to handle garbage collection by itself?
var imageBytes = Convert.FromBase64String(imageBase64String);
Bitmap m = ByteToBitmap(imageBytes);
public static Bitmap ByteToBitmap(byte[] imageByte)
{
using (MemoryStream mStream = new MemoryStream())
{
mStream.Write(imageByte, 0, imageByte.Length); // this will stream dataand handle image length by itself
mStream.Seek(0, SeekOrigin.Begin);
Bitmap bm = new Bitmap(mStream);
return bm;
}
}
For SVG,
public static Bitmap ByteToBitmap(byte[] imageByte)
{
using (MemoryStream mStream = new MemoryStream(imageByte))
{
var s= SvgDocument.Open(mStream);
var bm= svgDocument.Draw();
return bm;
}
}

Convert BitmapImage to byte[]

I have problem with converting BitmapImage to byte[]. I tried a lot of solutions and nothing works, every time i get different errors.
For example i found nice solutions but it also doesn't work. What's wrong with it?
I'm using Windows Phone 8.1.
public static byte[] ImageToBytes(BitmapImage img)
{
using (MemoryStream ms = new MemoryStream())
{
WriteableBitmap btmMap = new WriteableBitmap(img);
System.Windows.Media.Imaging.Extensions.SaveJpeg(btmMap, ms, img.PixelWidth, img.PixelHeight, 0, 100);
img = null;
return ms.ToArray();
}
}
this was taken from here: Convert Bitmap Image to byte array (Windows phone 8)
There is no argument given that corresponds to the required formal
parameter 'pixelHeight' of 'WriteableBitmap.WriteableBitmap(int, int)'
The type or namespace name 'Extensions' does not exist in the
namespace 'System.Windows.Media.Imaging' (are you missing an assembly
reference?)
or if somebody has got another idea how to convert it, please post it. Thanks a lot for any help!
I also tried this: BitmapImage to byte[]
but there was problem with usings
'BitmapImage' is an ambiguous reference between 'System.Windows.Media.Imaging.BitmapImage' and 'Windows.UI.Xaml.Media.Imaging.BitmapImage'
so I used "BitmapEncoder" but it doesn't have method like Save and Frame.
I think that it can't be done on this platform. I change my project to Windows Phone Silverlight/8.0 and there is working everything.
public static BitmapImage BytesToImage(byte[] bytes)
{
BitmapImage bitmapImage = new BitmapImage();
try
{
using (MemoryStream ms = new MemoryStream(bytes))
{
bitmapImage.SetSource(ms);
return bitmapImage;
}
}
finally { bitmapImage = null; }
}
public static byte[] ImageToBytes(BitmapImage img)
{
using (MemoryStream ms = new MemoryStream())
{
WriteableBitmap btmMap = new WriteableBitmap(img);
System.Windows.Media.Imaging.Extensions.SaveJpeg(btmMap, ms, img.PixelWidth, img.PixelHeight, 0, 100);
img = null;
return ms.ToArray();
}
}
see the below link it might help
https://social.msdn.microsoft.com/Forums/en-US/713c0ed1-d979-43ef-8857-bbe0b35576a9/windows-8-how-to-convert-bitmapimage-into-byte?forum=winappswithcsharp
Have you tried
MemoryStream ms = new MemoryStream();
WriteableBitmap wb = new WriteableBitmap(myImage);
wb.SaveJpeg(ms, myImage.PixelWidth, myImage.PixelHeight, 0, 100);
byte[] imageBytes = ms.ToArray();
You can also use extension method here
public static class MyExtensions
{
public static Byte[] ByteFromImage(this System.Windows.Media.Imaging.BitmapImage imageSource)
{
Stream stream = imageSource.StreamSource;
Byte[] imagebyte = null;
if (stream != null && stream.Length > 0)
{
using (BinaryReader br = new BinaryReader(stream))
{
imagebyte = br.ReadBytes((Int32)stream.Length);
}
}
return imagebyte;
}
}
and then call
System.Windows.Media.Imaging.BitmapImage myImage = new System.Windows.Media.Imaging.BitmapImage();
byte[] imageBytes = myImage.ByteFromImage();
If you're going to do any transformation on the image, you'll want to use the appropriate image encoder, then do something like below. If you're working with a multi-frame image (eg TIF), you need to add the frames one at a time to the encoder or you'll only get the first frame of the image.
MemoryStream ms = null;
TiffBitmapEncoder enc = null
enc = new TiffBitmapEncoder();
enc.Compression = TiffCompressOption.Ccitt4;
enc.Frames.Add(BitmapFrame.Create(bmpImg));
using (ms = new MemoryStream())
{
enc.Save(ms);
}
return ms.ToArray();

convert binary to bitmap using memory stream

Hi I wanna convert binary array to bitmap and show image in a picturebox. I wrote the following code but I got exception that says that the parameter is not valid .
public static Bitmap ByteToImage(byte[] blob)
{
MemoryStream mStream = new MemoryStream();
byte[] pData = blob;
mStream.Write(pData, 0, Convert.ToInt32(pData.Length));
Bitmap bm = new Bitmap(mStream);
mStream.Dispose();
return bm;
}
It really depends on what is in blob. Is it a valid bitmap format (like PNG, BMP, GIF, etc?). If it is raw byte information about the pixels in the bitmap, you can not do it like that.
It may help to rewind the stream to the beginning using mStream.Seek(0, SeekOrigin.Begin) before the line Bitmap bm = new Bitmap(mStream);.
public static Bitmap ByteToImage(byte[] blob)
{
using (MemoryStream mStream = new MemoryStream())
{
mStream.Write(blob, 0, blob.Length);
mStream.Seek(0, SeekOrigin.Begin);
Bitmap bm = new Bitmap(mStream);
return bm;
}
}
Don't dispose of the MemoryStream. It now belongs to the image object and will be disposed when you dispose the image.
Also consider doing it like this
var ms = new MemoryStream(blob);
var img = Image.FromStream(ms);
.....
img.Dispose(); //once you are done with the image.
System.IO.MemoryStream mStrm = new System.IO.MemoryStream(your byte array);
Image im = Image.FromStream(mStrm);
im.Save("image.bmp");
Try this. If you still get any error or exception; please post your bytes which you are trying to convert to image. There should be problem in your image stream....

Categories