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).
Related
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.
I am looking to convert PDF files into images. Docnet is able to convert the pdf into bytes[] and their samples show how to save this byte[] into an image file using Bitmap. Documentation
However, the solution won't work on linux machine since Bitmap requires few libraries pre-installed on the system.
I've tried ImageSharp to convert the byte[] using SixLabors.ImageSharp.Image.Load<Bgra32>(rawBytes), however, it throws Unhandled exception. SixLabors.ImageSharp.InvalidImageContentException: PNG Image does not contain a data chunk.
Does anyone knows any alternative to achieve this.
PS - I'm open to explore any other cross platform FREE supported alternatives to convert PDF files to images.
This works fine with ImageSharp assuming Docnet works then ImageSharp will work fine for you.
The trick is you want to be using the Image.LoadPixelData<Bgra32>(rawBytes, width, height); API not the Image.Load<Bgra32>(encodedBytes); one.
using Docnet.Core;
using Docnet.Core.Models;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using var docReader = DocLib.Instance.GetDocReader(
"wikipedia_0.pdf",
new PageDimensions(1080, 1920));
using var pageReader = docReader.GetPageReader(0);
var rawBytes = pageReader.GetImage();
var width = pageReader.GetPageWidth();
var height = pageReader.GetPageHeight();
// this is the important line, here you are taking a byte array that
// represents the pixels directly where as Image.Load<Bgra32>()
// is expected an encoded image in png, jpeg etc format
using var img = Image.LoadPixelData<Bgra32>(rawBytes, width, height);
// you are likely going to want this as well otherwise you might end up with transparent parts.
img.Mutate(x => x.BackgroundColor(Color.White));
img.Save("wikipedia_0.png");
I'm using C#, and need to process Jpeg-XR images. However, these images are presented in form of base64 strings, and need to be converted into Bitmap objects directly. I can write it into a file and convert it, but this significantly affects my running time.
I was wondering if anyone could help me with a sample code, or a hint?
(I already tried Magick.Net, but that didn't work for me, and also doesn't seem to be able to load a JXR image directly).
thanks a lot
JPEG XR is formerly known as HD Photo and Windows Media Photo.
You can use the class WmpBitmapDecoder in System.Windows.Media.Imaging in the WPF library to manipulate .jxr images.
This class Defines a decoder for Microsoft Windows Media Photo encoded images.
The following code convert JXR file to Bmp file:
using System.IO;
using System.Windows.Media.Imaging;
public class JXrLib
{
public static void JxrToBmp(string source, string target)
{
Stream imageStreamSource = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.Read);
WmpBitmapDecoder decoder = new WmpBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
BitmapSource bitmapSource = decoder.Frames[0];
var encoder = new BmpBitmapEncoder(); ;
encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
using (var stream = new FileStream(target, FileMode.Create))
{
encoder.Save(stream);
}
}
}
The code is tested and running fine.
Alternative 2:
If you are interested of using Magick.Net, you can use jxrlib library in https://jxrlib.codeplex.com
Copy the file JXRDecApp.exe and JXREncApp.exe to your bin directory and read from a file on disk that has a .jxr extension.
(you have to compile jxrlib using visual studio)
Code example:
// Read first frame of jxr image
//JXRDecApp.exe ,JXREncApp.exe should be located in the path of binaries
using (MagickImage image = new MagickImage(#"images\myimage1.jxr"))
{
// Save frame as bmp
image.Write("myimage2.bmp");
// even , Save frame as jxr
image.Write("myimage2.jxr");
}
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!
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.