Using BmpBitmapEncoder for all image formats - c#

I found that using BmpBitmapEncoder to render any type of image works, the only thing I'd need to do is send the correct format in the file to be saved as in the following example:
BmpBitmapEncoder encoder = new BmpBitmapEncoder();;
encoder.Frames.Add(BitmapFrame.Create(renderer));
using (System.IO.FileStream fs = System.IO.File.Open("file.png", System.IO.FileMode.OpenOrCreate))
{
encoder.Save(fs);
}
So, as you can see, the name of the image is "file.png", and this works correctly, it saves the image as PNG (also works with jpeg, tiff, gif), and it can be loaded with any image processing application.
I just want to know how is this different from using the correct encoder for each type (PngBitmapEncoder, JpegBitmapEncoder, GifBitmapEncoder, etc) instead.
Thank you.

You MUST use the right encoder PngBitmapEncoder, JpegBitmapEncoder, GifBitmapEncoder.
The file you are saving this way is ALWAYS a BMP!
What is happening in your test is that the image processing application you are using is ignoring the extension and recognizing the real file format as a BMP.

Related

How can I get image content as pixel and create image from it in ASP.NET Core 6 Web API?

I try to save my images on my server, but I can't let my server save file and virus because of that I want to get image content as pixels of rgb and after that I create image by myself.
I can't use bitmap (or other type in C# like bitmapImage, ... etc) and I don't know how I can do this with sixlabors.ImageSharp.
I have some code that I tried but I can't implement the exact logic that I want (code shown here):
[HttpPost("[action]")]
public async Task<IActionResult> Get([FromForm] ImageFormat file)
{
await using var memoryStream = new MemoryStream();
await file.File.CopyToAsync(memoryStream);
IImageFormat format;
using (var image = Image.Load(memoryStream.ToArray(), out format))
{
using (var output = new MemoryStream())
{
image.Save(output, format);
var responseType = format.Name.ToLower();
return File(output.ToArray(), "application/octet-stream", file.File.FileName);
}
}
return null;
}
Can anybody help me with this problem?
i don't see a reason to convert image into image: there are several format zip-algorythms etc.wich you have to support in that case. example jpg is not bitmap, there is convertion issue - quality of image becomes less each conversion time. Image itself is not executable - it can be used only as container for virus body, can't harm your OSystem itself, another executable part should works somewhere.
But even if you would like to store images on disk, in other format - you can convert image to base64 text (one line of code, like example) - it less harmful and well known way to work with any file type. you can zip image by cszip, you can change file name and extension to hide file type.
I don't see a reasson to convert one image to another for this scenario/task.

How do I create/edit a PNG file in C#?

I've written a program that can create digital art. Images like the Mandelbrot Set and the Julia Set. But I'm looking to save these images as PNGs. At present, in Java, I'm generating the images in an application window and then taking a screen shot of the display. However, I lose the finer detail of these images. Plus, this method also reduces the physical size of the images as well. I want to potentially be able to make a big poster out of these pictures.
In C#, I'm using the following:
Bitmap myimage = new Bitmap("image.png"); and: myimage.SetPixel(x,y, Color.FromArgb(255*colors[x,y], 255*colors[x,y], 255*colors[x,y]); where colors[,] is some value between 0 and 1.
The code runs fine, minus the Bitmap declaration. My understanding is that new Bitmap(filepath); allows you to edit and manipulate the PNG image. Am I right to think that? How do I create/edit a PNG file in C#?
(edit)PS: The PNG file, "image.png", does exist in the solution folder.
Firstly you have to know the step by step process in creating the PNG file.
Setup Aspose.Imaging for .NET package from Nuget.org.
Include reference to following two namespaces: Aspose.Imaging,
Aspose.Imaging.ImageOptions.
Specify license using SetLicense method before converting.
Read BMP file into an Image object.
Set attributes for output PNG image using PngOptions class.
Save the output PNG image with the specified PNG options.
Code to create PNG image from BMP
using System;
//Use following namespaces to create PNG image
using Aspose.Imaging;
using Aspose.Imaging.ImageOptions;
namespace CreatePNGImage
{
class Program
{
static void Main(string[] args)
{
//Set license before creating PNG image from BMP
Aspose.Imaging.License AsposeImagingLicense = new Aspose.Imaging.License();
AsposeImagingLicense.SetLicense(#"c:\asposelicense\license.lic");
//load input BMP image
Image BmpToPngImage = Image.Load("InputBMPImage.bmp");
//set attributes of the output PNG file
PngOptions PNGImageOptions = new PngOptions();
PNGImageOptions.ResolutionSettings = new ResolutionSetting(300, 300);
PNGImageOptions.CompressionLevel = 6;
//save converted output PNG image
BmpToPngImage.Save("OutputPNGImage.png", PNGImageOptions);
}
}
}
Try this to create the PNG file out of c#.

How load an image from disk and save to a stream using ImageSharp while preserving the mimetype

I've got a bunch of images stored on disk, with the mimetype of the image stored in a database. If I want to save the image to disk I can use Image.Save(string) (or the Async version) without needing to know the MimeType of the image.
However, if I want to save to a stream (for example, Response.Body) then I have to use Image.Save(Stream, IImageEncoder).
How do I get the IImageEncoder I need to save to the stream (without just declaring that "All my images ar png/jpeg/bmp" and using e.g. JpegEncoder)?
ImageSharp can already tell you the mimetype of the input image. With your code if the
mimetype doesn't match the input stream then the decode will fail.
(Image Image, IImageFormat Format) imf = await Image.LoadWithFormatAsync(file.OnDiskFilename);
using Image img = imf.Image;
img.Save(Response.Body, imf.Format);
What we are missing however in the current API v1.0.1 is the ability to save asynchronously while passing the format. We need to add that.
It took a bit of messing about, but I've figured it out:
var file = ... // From DB
ImageFormatManager ifm = Configuration.Default.ImageFormatsManager;
IImageFormat format = ifm.FindFormatByMimeType(file.MimeType);
IImageDecoder decoder = ifm.FindDecoder(format);
IImageEncoder encoder = ifm.FindEncoder(format);
using Image img = await Image.LoadAsync(file.OnDiskFilename, decoder);
// Do what you want with the Image, e.g.: img.Mutate(i => i.Resize(width.Value, height.Value));
Response.ContentType = format.DefaultMimeType; // In case the stored mimetype was something weird
await img.SaveAsync(Response.Body, encoder);
(Although I'm happy to be shown a better way)

Set image resolution

I have array of image bytes and I would like to set resolution. Original image can be JPEG, PNG, BMP. Output - PNG. I am using ImageMagic to convert image and do some manipulations.
using (var image = this.Convert(originalImage, height, width))
using (var stream = new MemoryStream())
{
image.Quality = 90;
image.Write(stream, MagickFormat.Png);
return stream.GetBuffer();
}
I tryed to modify image.GetExifProfile, but has no success (at least for PNG images).
I can't use any comandline tool (like ImageMagic or ExifTool) here.
There are 3 exiff tags I need to modify
XResolution
YResolution
ResolutionUnit
I can successfully achieve this with bitmap, but it also resource overhead (need to create MemoryStream ...).
I have found some Pdf specification, but it will consume time to make it all work.
Does any can point me to right direction?
Thanks.

How to save image stream in c#?

I have a imagestream in c# and i want to save them on the hard drive using the c# code. when i trying to do that i found Out of Memory whennever i have much enough Memory.
so i am sure that my code leak the resources so can someone show me how i can do that
HttpPostedFileBase file
file.SaveAs(location);
Image image = Image.FromFile(location,false);
image.Save(location, System.Drawing.Imaging.ImageFormat.Png);
image.fromFile line [3] caused Exception that out of Memory. can someone show me how i can do this in c#.
The file come from PNG using Ajax Request are come as octet type as Mime type so how i can do that.
Assuming you want to convert the image to PNG (otherwise there's no need to save the image once, reload it and re-save it again), it might be a good idea to avoid loading the image twice. See if something like this helps:
Image.FromStream(file.InputStream, false).Save(location, System.Drawing.Imaging.ImageFormat.Png);
file.SaveAs(location);
already saved the image at the given location or threw an exception, so the following lines are unnecessary.
Bitmap bmp = new Bitmap(file.InputStream);
bmp.Save(filename, ImageFormat.Png);

Categories

Resources