Create image from stream with correct pixel format - c#

I created a web service in .Net Core. This service return an image png with pixel format 8pp indexed :
using (Bitmap bmp = new Bitmap(img.width, img.height, PixelFormat.Format8bppIndexed))
{
using (MemoryStream ms = new MemoryStream())
{
bmp.Save(ms, imgFormat);
return new FileContentResult(ms.ToArray(), $"image/png");
}
}
I want to test this service, so I created a C# test with this piece of code :
Task<HttpResponseMessage> responseTask = client.PostAsync(url, content);
responseTask.Wait();
var response = responseTask.Result;
HttpContent ct = response.Content;
byte[] data = await ct.ReadAsByteArrayAsync();
using (MemoryStream m = new MemoryStream(data))
{
Bitmap img = new Bitmap(m);
img.Save(filePath, ImageFormat.Png);
}
But the Bitmap img is Format32bppArgb. How can I do to get my image in original format (Format8bppIndexed) ?

Just save straighway what you got:
using (var fs = new FileStream(filePath, FileMode.Create))
fs.Write(data, 0, data.Length);

Related

Convert Xamarin bitmap to byte[] not work or throw exception

I tried to convert my image from camera to byte[] and then make request to my server but it is not working so my image from camera is
var image = textureView.Bitmap;
image = Android.Graphics.Bitmap.CreateBitmap
(image,
(int)OCR_Rectangle.GetX(),
(int)OCR_Rectangle.GetY(),
OCR_Rectangle.Width,
OCR_Rectangle.Height);
My web request is
public async static Task<string> ParseAsync(byte[] image)
{
string id = "my id ";
string apiKey = "my api key ";
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("app_id", id);
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("app_key", apiKey);
var base64 = Convert.ToBase64String(image);
var imageUri = "data:image/jpg;base64," + base64;
var json = JsonConvert.SerializeObject(new { src = imageUri });
var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync("my website", content);
var dynObj = JsonConvert.DeserializeObject<RootObjectLatex>(await response.Content.ReadAsStringAsync());
return dynObj.latex;
}
}
Here is my attempt to convert bitmap to byte[]
byte[] bitmapData;
using (var stream = new MemoryStream())
{
image.Compress(Bitmap.CompressFormat.Png, 0, stream);
bitmapData = stream.ToArray();
}
And then i want to use bitmapData in my request.But no luck.
So, I found error this works
byte[] bitmapData;
using (var stream = new MemoryStream())
{
image.Compress(Bitmap.CompressFormat.Png, 0, stream);
bitmapData = stream.ToArray();
}
but i type wrong api key in my request

How can i clear the memory after converting BitmapImage to Byte

I have two functions: one to convert from image to byte and other to convert from byte to bitmapImage.
So, when I open the window with that images, I convert from byte to bitmapImage and it works great, but when I close and open it again it just keeps on memory and if I continue to do that time and time again it just throws an exception Out Of Memory exception
Image to byte->
private byte[] ConvertImageToBinary(Image img)
{
using (MemoryStream ss = new MemoryStream())
{
img.Save(ss, System.Drawing.Imaging.ImageFormat.Jpeg);
var s = ss.ToArray();
var jpegQuality = 50;
Image image;
using (var inputStream = new MemoryStream(s))
{
image = Image.FromStream(inputStream);
var jpegEncoder = System.Drawing.Imaging.ImageCodecInfo.GetImageDecoders()
.First(c => c.FormatID == System.Drawing.Imaging.ImageFormat.Jpeg.Guid);
var encoderParameters = new System.Drawing.Imaging.EncoderParameters(1);
encoderParameters.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, jpegQuality);
Byte[] outputBytes;
using (var outputStream = new MemoryStream())
{
image.Save(outputStream, jpegEncoder, encoderParameters);
return outputBytes = outputStream.ToArray();
}
}
}
}
Byte to bitmap ->
public BitmapImage ConvertBinaryToImage(byte[] array)
{
var image = new BitmapImage();
using (var ms = new MemoryStream(array))
{
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad; // here
image.StreamSource = ms;
image.EndInit();
image.Freeze();
}
return image;
}
When I open the WindowDragAndDrop it loads all the images
But when I close it it still uses the same amount of memory
Image is indeed disposable (https://learn.microsoft.com/en-us/dotnet/api/system.drawing.image?view=netframework-4.8), so you also need:
using (var image = Image.FromStream(inputStream)){
}
Around everywhere you use Image objects.

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;
}
}

C# MVC save View as png

i have problem with png HTML renderer,
i am trying to send png of View to email, but on email i get 0B .png
PS: Ticket.pdf is ok
using (MemoryStream ms = new MemoryStream())
{
var pdf = PdfGenerator.GeneratePdf(RenderRazorViewToString("TicketTemplateBig", model), PdfSharp.PageSize.A4);
pdf.Save(ms, false);
/////////////////
//Bitmap bitmap = new Bitmap(Convert.ToInt32(1024), Convert.ToInt32(1024), System.Drawing.Imaging.PixelFormat.Format32bppArgb);
using (MemoryStream ms2 = new MemoryStream())
{
//Image image = TheArtOfDev.HtmlRenderer.WinForms.HtmlRender.RenderToImage(RenderRazorViewToString("TicketTemplateBig", model));
Bitmap bitmap = (Bitmap)Image.FromFile(#"C:\logo.png");
bitmap.Save(ms2, ImageFormat.Png);
/////////////////
await ms.FlushAsync();
await ms2.FlushAsync();
mm.Attachments.Add(new Attachment(ms, string.Format("Ticket.pdf"), "application/pdf"));
streams.Add(ms);
mm.Attachments.Add(new Attachment(ms2, string.Format("logo.png"), "application/png"));
streams.Add(ms2);
await client.SendMailAsync(mm);
}
}
You are trying to send the mail before having effectively written to ms2.
you need to do flush the ms2 stream buffer before adding it to mm . (as you did for ms, that's why the pdf part was handled correctly)
(Also, minor typo : "application/png" instead of "application/Png", probably not an issue)
problem : stream was on last position
result : ms2.Position = 0;
using (MemoryStream ms = new MemoryStream())
{
var pdf = PdfGenerator.GeneratePdf(RenderRazorViewToString("TicketTemplateBig", model), PdfSharp.PageSize.A4);
pdf.Save(ms, false);
using (MemoryStream ms2 = new MemoryStream())
{
Image image = TheArtOfDev.HtmlRenderer.WinForms.HtmlRender.RenderToImage(RenderRazorViewToString("TicketTemplateBig", model));
image.Save(ms2, ImageFormat.Png);
ms2.Position = 0;
await ms.FlushAsync();
await ms2.FlushAsync();
mm.Attachments.Add(new Attachment(ms, string.Format("Ticket.pdf"), "application/pdf"));
mm.Attachments.Add(new Attachment(ms2, string.Format("Ticket.png"), "application/png"));
await client.SendMailAsync(mm);
}
}
Thanks Guys

C# Load JPG file, extract BitmapImage

I am trying to extract a BitmapImage from a JPG. This is the code I have:
FileStream fIn = new FileStream(sourceFileName, FileMode.Open); // source JPG
Bitmap dImg = new Bitmap(fIn);
MemoryStream ms = new MemoryStream();
dImg.Save(ms, ImageFormat.Jpeg);
image = new BitmapImage();
image.BeginInit();
image.StreamSource = new MemoryStream(ms.ToArray());
image.EndInit();
ms.Close();
image comes back with a 0 × 0 image, which of course means it didn't work. How do I do this?
Try this:
public void Load(string fileName)
{
using(Stream BitmapStream = System.IO.File.Open(fileName,System.IO.FileMode.Open ))
{
Image img = Image.FromStream(BitmapStream);
mBitmap=new Bitmap(img);
//...do whatever
}
}
Or you can just do this (source):
Bitmap myBmp = Bitmap.FromFile("path here");

Categories