Creating a PNG source from data in memory - c#

Situation:
I am reading a PNG file, encoded with base64 from a server (JSON Format). Works fine.
There is NO direct URL to the ressource (just like: http:... / image.png or simuliar), so i read the data (which is part of a JSON object), decode in from the base64 Encoding and store it in a byte[].
Want i want: Display this PNG on a certain page ( like:
ImageOnPage.Source = myPNG;
)
I cant find a way to make PNG-data to a bitmap. With jpegs i could do something like
using (var stream = new MemoryStream(data, 0, x, true, true)) {
var wbp = new WriteableBitmap(1, 1);
wbp.LoadJpeg(stream);
profileImage.Source = wbp;
}
(sorry, code not testet)
I tried to look around and find the PNG Writer Library - but i still didn't find a way to do something to convert my internal PNG to a useable Bitmap for Setting the Image.Source.
Any help appreciated!

Related

In Unity trying to convert a Base64String to a png

I'm getting a Base64String from an API (Stable Horde)
I tried using
filePath = some path + image.png
File.WriteAllBytes(filePath, Convert.FromBase64String(myImageData.generations[0].img));
This does create an image on the hard drive but its not really a png image so when I try to read all bytes
back into an image in the scene there is a problem. Doesn't work. I figured out that this is because it was not encoded correctly into a real png in the first place.
I'm trying to translate this python code (into Unity C#) that does create an actual png:
b64img = results[iter]["img"]
base64_bytes = b64img.encode('utf-8')
img_bytes = base64.b64decode(base64_bytes)
img = Image.open(BytesIO(img_bytes))
if len(results) > 1:
final_filename = f"{iter}_{filename}"
img.save(final_filename)
I've been trying solutions searching online for about 16 hours with no luck. Can't believe how poorly documented and hard to do this is?
Can anyone help? What's the correct way to take a Base64String and convert it to a png in Unity C#.
Thanks!
Try this:
string base64String = "(your base64 string)";
byte[] data = System.Convert.FromBase64String(base64String);
Texture2D texture = new Texture2D(0, 0);
ImageConversion.LoadImage(texture, data);

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 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)

Save XAML Image into file in metro apps

i convert a PDF file to BitmapImage in C#. After i manipulate it (resize, rotate) and i want to save it to new PNG or JPEG file but i'm not found how can i make that. I'm developed a windows store apps in C#.
According to this blog post: Save XAML as PNG in a Windows Store App
You should be able to do this using the class BitmapEncoder, the method BitmapSource.CopyPixels will give you the pixels data that BitmapEncoder requires.
Use LibPdf, for PDF to Image conversion
This library converts converts PDF file to an image. Supported image formats are PNG and BMP, but you can easily add more.
Usage example:
using (FileStream file = File.OpenRead(#"..\path\to\pdf\file.pdf")) // in file
{
var bytes = new byte[file.Length];
file.Read(bytes, 0, bytes.Length);
using (var pdf = new LibPdf(bytes))
{
byte[] pngBytes = pdf.GetImage(0,ImageType.PNG); // image type
using (var outFile = File.Create(#"..\path\to\pdf\file.png")) // out file
{
outFile.Write(pngBytes, 0, pngBytes.Length);
}
}
}
ImageMagick, you should also look at this freely available and powerful tool. It's capable of doing what you want and also provides some .NET bindings (as well as bindings to several other languages).

Efficient way to upload images in SQP.NET

I am still very much learning ASP.NET using c# and Webmatrix. I have put together a photography competition site but can't quite find an ideal way of uploading images. I don't see the point of uploading images greater than 1200x900 (projectors maximum resolution) so want to make sure images are small as possible.
I am using tag and checking he image size. If it's too big I am using 'ImageResizer' to resize the image when saving. The only way I know to check the size is to convert the 'HttpPostedFileBase' file into an image using System.Drawing.Image. But when the image is 36Mpixels (it is a photography club) this is taking an age just to read the height and width properties. Can I just load the first x bytes to read the properties or do I have to read the whole image?
The second reason I am converting to an image is to extract the exif data. Again is there an easier and quicker way to read the exif data?
I hope my question makes sense this is all a bit new to me.
simplified code:
HttpPostedFileBase uploadedFile = Request.Files[0];
using (System.Drawing.Image image = System.Drawing.Image.FromStream(uploadedFile.InputStream, true, true))
{
string Exif;
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
try{
Exif = encoding.GetString(image.GetPropertyItem(36867).Value);
}
catch
{
Exif="";
}
if (image.Width <Convert.ToInt32(MaxWidth) && image.Height <Convert.ToInt32(MaxHeight))
{
// SAVE IMAGE AS IS
image.Save(fileSavePath);
// LOAD IMAGE DETAILS WITH EXIF
db.Execute("INSERT INTO CompImages (ImageTitle,CompID,GroupID,ClubID,FileName,UserID,ExifDate) VALUES(#0,#1,#2,#3,#4,#5,#6)",ImageTitle,CompID,GroupID,ClubID,fileName,WebSecurity.CurrentUserId,DateTaken);
}
else
{
// LOAD IMAGE DETAILS WITH EXIF
db.Execute("INSERT INTO CompImages (ImageTitle,CompID,GroupID,ClubID,FileName,UserID,ExifDate) VALUES(#0,#1,#2,#3,#4,#5,#6)",ImageTitle,CompID,GroupID,ClubID,fileName,WebSecurity.CurrentUserId,DateTaken);
// RESIZE IMAGE
ImageResizer.ImageJob iF = new ImageResizer.ImageJob(image, "~/UpImages/"+CompID+"/"+fileName, new ImageResizer.ResizeSettings(
"width="+MaxWidth+";height="+MaxHeight+";format=jpg;mode=max"));
iF.CreateParentDirectory = true; //Auto-create the uploads directory.
iF.Build();
}
}
The only way I know to check the size is to convert the
'HttpPostedFileBase' file into an image using System.Drawing.Image.
You could also checkout the ContentLength property directly:
int uploadedFileSize = uploadedFile.ContentLength;
The second reason I am converting to an image is to extract the exif
data. Again is there an easier and quicker way to read the exif data?
I am not aware of a built-in class in the BCL that would allow you to read EXIF information without loading the image in memory but you could use some third party library like this one: http://www.codeproject.com/Articles/36342/ExifLib-A-Fast-Exif-Data-Extractor-for-NET-2-0

Categories

Resources