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#.
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.
In my App i generate an PDF-File with PDFSharp.Xamarin which I got from this site:
https://github.com/roceh/PdfSharp.Xamarin
Everything is working fine.
In my PDF-Document I have many Images, which are compressed.
But the file size of my PDF-Document is too large.
Is there a possibility to compress my PDF-Document before saving it?
How can I work with the PdfSharp.SharpZipLib.Zip Namespace to deflate the file size?
UPDATE:
Here is my Code:
document = new PdfDocument();
document.Info.Title = nameDok.Replace(" ", "");
document.Info.Author = "---";
document.Info.CreationDate = DateTime.Now;
document.Info.Subject = nameDok.Replace(" ", "");
//That is how i add Images:
XImage image = XImage.FromStream(lstr);
gfx.DrawImage(image, 465, YPrev - 2, newimagewf, newimagehf);
document.CustomValues.CompressionMode = PdfCustomValueCompressionMode.Compressed;
document.Options.FlateEncodeMode = PdfFlateEncodeMode.BestCompression;
document.Save(speicherPfad);
Thanks for everyone.
I only know the original PDFsharp, not the Xamarin port: images are deflated automatically using SharpZipLib.
Make sure to use appropriate source images (e.g. JPEG or PNG, depending on the image).
On the project start page they write:
"Currently all images created via XGraphics are converted to jpegs with 70% quality."
This could mean that images are re-compressed, maybe leading to larger files than before.
Take one JPEG file, convert it to PDF, and check the size of the image (in bytes) in the PDF file.
I'm trying to convert a .png file to a .pcx file. The scenario is the following:
I'm using a TSC TTP-343C label printer. On the labels I have to print images. TSC provides a library documentation for developers. Since I can only print images on those labels using pcx files I have to convert all the images to pcx images. Any other format or even incorrect pcx format (e.g. if the user just renamed the file ending) will not be printed on the label.
I've seen this post linking to the Magick library. In this post, the OP is trying to convert a bmp file to a pcx file which is not exactly what I try to achieve. I looked at the Magick documentation about converting images. I tried to convert the images like:
using (MagickImage img = new MagickImage(png)) // png is a string containing the path of the .png file
{
img.Format = MagickFormat.Pcx;
img.Write(pcx); // pcx is a string containing the path of the new .pcx file
}
Unfortunately this is not saving the image correctly. The label printer still cannot print the image on the label. I tried printing a correct pcx file and this worked fine. So I guess the only reason why it's still not working is that the converted file is not a real pcx file.
Is there a way to do such a conversion? If yes, how can I achieve that? My application is a windows forms application, written in C# using .NET framework 4.5.2.
EDIT:
Here you can see an example how to print a label with a pcx file:
TSC.openport(sPrinterName);
TSC.setup("100", "100", "4", "8", "1", "3.42", "0");
TSC.clearbuffer();
TSC.downloadpcx(#"\\PathToPcxFile\test.pcx", "test.pcx");
TSC.sendcommand("PUTPCX 35," + y + ",\"test.pcx\"");
TSC.printlabel("1", "1");
TSC.closeport();
This code works fine on real pcx files. The methods of the TSC library can you find here.
downloadpcx(a,b)
Description: Download mono PCX graphic files to the printer Parameter:
a: string; file name (including file retrieval
path)
b: string, names of files that are to be downloaded in the
printer memory (Please use capital letters)
Source: http://www.tscprinters.com/cms/upload/download_en/DLL_instruction.pdf
EDIT II:
A pcx file which is working (created using photoshop) looks like this (if it helps you):
PCX files are (at best) palette-based.
So to create a valid pcx output you need to add this one line:
using (MagickImage image = new MagickImage(sourcePng))
{
image.Format = MagickFormat.Pcx;
image.ColorType = ColorType.Palette; // <----
image.Write(targetPcx);
}
Your image as pcx file
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
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.