c# chart.object from excel as .png low resolution - c#

I have created an excel file and want to export its contents as a png or jpeg file.
Unfortunately the quality of the image is really low.
Is there a solution to this? I wish a really high resolution picture.
Thank you
My current code (from internet):
Excel.Range xlRange = xlWorksheet5.get_Range("A1", "K30");
xlRange.CopyPicture(Excel.XlPictureAppearance.xlScreen, Excel.XlCopyPictureFormat.xlPicture);
Excel.ChartObject chartObj;
chartObj = xlWorksheet5.ChartObjects().Add(xlRange.Left, xlRange.Top, xlRange.Width, xlRange.Height);
chartObj.Activate();
string path_image = path + "\\image.png";
Excel.Chart chart = chartObj.Chart;
chart.Paste();
chart.Export(path_image);

Try this. You'll need to put a [STAThread] attribute over the entry point of whatever thread you run this on.
//This first copy/paste is to convert from chart to image
chartObj.CopyPicture();
xlWorksheet5.Paste();
//This image has decent resolution
xlWorksheet5.Shapes.Item(xlWorksheet5.Shapes.Count).Copy();
//Save the image
System.Windows.Media.Imaging.BitmapEncoder enc = new System.Windows.Media.Imaging.BmpBitmapEncoder();
enc.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(System.Windows.Clipboard.GetImage()));
using (System.IO.MemoryStream outStream = new System.IO.MemoryStream())
{
enc.Save(outStream);
System.Drawing.Image pic = new System.Drawing.Bitmap(outStream);
pic.Save("image.png");
}

Related

C# .svg file to System.Drawing.Image

I need to convert the selected .svg file to System.Drawing.Image object, so I can resize it and save it as .png. Can anyone help me with this?
Here is what I have so far:
Svg.SvgDocument svgDocument = SVGParser.GetSvgDocument(mPath);
image = svgDocument.Draw();
But it gives me out of memory error.
You can use the SVG Rendering Engine Lib:
Install-Package Svg
It's quite easy to draw images using it:
var svgDoc = SvgDocument.Open(imagePath);
using(var Image = new Bitmap(svgDoc.Draw()))
{
Image.Save(context.Response.OutputStream, ImageFormat.Png);
context.Response.ContentType = "image/png";
context.Response.Cache.SetCacheability(HttpCacheability.Public);
context.Response.Cache.SetExpires(DateTime.Now.AddMonths(1));
}
In this example i'm using a handler to display the image on the browser but you can easily save it on some folder just by changing the first parameter of the Save method.
The resource Miljan Vulovic used is svg (https://archive.codeplex.com/?p=svg).
Link is only valid until July 2021, it might be available on GitHub by then, but I'm not sure.
Anyways his solution works for me.
So,
SVGParser.MaximumSize = new System.Drawing.Size(4000, 4000);
svgDocument = SVGParser.GetSvgDocument(mPath);
var bitmap = svgDocument.Draw();
image = bitmap;

C# iTextSharp Extracted CMYK images returns in RGB Format

I am using iTextsharp to extracted images from epaper PDF files, the images in the PDF files are in CMYK format, but the extracted images are in RGB. Please advice on this. Thanks in advance
int xrefIdx = ((PRIndirectReference)obj).Number;
PdfObject pdfObj = doc.GetPdfObject(xrefIdx);
PdfStream str = (PdfStream)pdfObj;
byte[] bytes = PdfReader.GetStreamBytesRaw((PRStream)str);
using (System.IO.MemoryStream memStream = new System.IO.MemoryStream(bytes))
{
var rawImage = System.Drawing.Image.FromStream(memStream);
rawImage.Save(#"e:\extractedimages.jpeg", ImageFormat.Jpeg);
}
Unfortunately, .NET isn't really up to the job for what you need to do as it really only works in RGB. Please see this answer to another question (https://stackoverflow.com/a/1773496/7122) which has more details.

Saving an captured image to the local folder

I am taking pictures and would like to save them according to the time they were exactly taken.
I would also like to create a folder named /pictures in the current directory and save the pictures in that folder. This is done in C# & WPF.
This is my code:
Image newimage = new Image();
BitmapImage myBitmapImage = new BitmapImage();
myBitmapImage.BeginInit();
newimage.Source = Capture(true) // Take picture
myBitmapImage.UriSource = new Uri(#"c:\" +
string.Format("{0:yyyy-MM-dd_hh-mm-ss-tt}", DateTime.Now) + ".jpg");
// Gives error: Could not find file 'c:\2013-05-26_04-40-25-AM.jpg'
myBitmapImage.EndInit();
newimage.Source = myBitmapImage;
newstackPanel.Children.Add(newimage);
Results in:
ERROR Could not find file 'c:\2013-05-26_04-44-59-AM.jpg'.
Why is it trying to find a file VS just saving the file on the c:\ drive?
If all you want to do is to save the image to disk, then you should use the BitmapEncoder class
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
var image = Capture(true); // Take picture
encoder.Frames.Add(BitmapFrame.Create(image));
// Save the file to disk
var filename = String.Format("...");
using (var stream = new FileStream(filename, FileMode.Create))
{
encoder.Save(stream);
}
The above example creates a JPEG image, but you any encoder you want - WFP comes with Png, Tiff, Gif, Bmp and Wmp encoders built in.

How to export a image to act file

I'm trying to create a mini tool for my job. I'm using C# with Visual Studio 2010 to do that. Now I need to export an image to an act file.
Following here, http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmappalette.aspx
I wrote
class Palette : List<Color>
{
public static Palette GetFromImage(String PathToImage)
{
//Load imgae
BitmapImage image = new BitmapImage();
image.BeginInit();
image.UriSource = new Uri(PathToImage, UriKind.RelativeOrAbsolute);
image.EndInit();
//Load palette
BitmapPalette BitmapPalette = new BitmapPalette(image, 256);
//Convert it to list of Color
Palette pal = new Palette();
for (int i = 0; i < BitmapPalette.Colors.Count; i++)
{
pal.Add(Color.FromArgb(BitmapPalette.Colors[i].R, BitmapPalette.Colors[i].G, BitmapPalette.Colors[i].B));
}
//Return the palette has been creatted
return pal;
}
This code has effected, but the order of all colors in the result did not same as the order of all colors when I export by photoshop. So, when I write all colors to a act file, the act file is not correct.
Anybody can help me.
Many thank
Act file is compilated binary file.
You cannot encode an act file.
Perhaps Photoshop can import a css file (as like palet)

Saving an image

I'm making a drawing program in C# for Windows Phone.
This is for Windows Phone, so a bunch of stuff doesn't work that would work in C#.
At the start of opening a .XAML page, I have a blank Canvas. The user draws on the Canvas, then clicks Save. When he/she clicks Save, I want the program to be able to save the image on the Canvas.
I have the following code so far:
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
StreamReader sr = null;
sr = new StreamReader(new IsolatedStorageFileStream("Data\\imagenum.txt", FileMode.Open, isf));
test = sr.ReadLine();
sr.Close();
int.TryParse(test, out test2);
test2 = test2 + 1;
IsolatedStorageFile isf2 = IsolatedStorageFile.GetUserStoreForApplication();
isf2.CreateDirectory("Data");
StreamWriter sw = new StreamWriter(new IsolatedStorageFileStream("Data\\imagenum.txt", FileMode.Create, isf2));
sw.WriteLine(test2);
//This writes the content of textBox1 to the StreamWriter. The StreamWriter writes the text to the file.
sw.Close();
This code finds what an appropriate name for the image would be.
I've also found various other code snippets on the web:
// Construct a bitmap from the button image resource.
test = "Images/" + test + ".jpg";
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
WriteableBitmap bmImage = new WriteableBitmap(image);
if (!store.DirectoryExists("Images"))
{
store.CreateDirectory("Images");
}
using (IsolatedStorageFileStream isoStream =
store.OpenFile(#"Images\" + test + ".jpg", FileMode.OpenOrCreate))
{
Extensions.SaveJpeg(
bmImage,
isoStream,
bmImage.PixelWidth,
bmImage.PixelHeight,
0,
100);
}
}
The above is an ugly mess of code from tutorials on MSDN and my own badly scraped together code.
(It doesn't work, for semi-obvious reasons)
How would I save the canvas to IsolatedStorage, as an image?
Your first section where you appear to be writing the last used number to a text file in IsolatedStorage seems like a lot of work to do something relatively simple. You can replace that whole section with this:
IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
int imageNumber = 0;
settings.TryGetValue<int>("PreviousImageNumber", out imageNumber);
imageNumber++;
You can save the image to IsolatedStorage like this:
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!isf.DirectoryExists("Images"))
{
isf.CreateDirectory("Images");
}
IsolatedStorageFileStream fstream = isf.CreateFile(string.Format("Images\\{0}.jpg",imageNumber));
WriteableBitmap wbmp = new WriteableBitmap(image);
Extensions.SaveJpeg(wbmp, fstream, wbmp.PixelWidth, wbmp.PixelHeight, 0, 100);
fstream.Close();
}
But it would probably make more sense to save the image to their MediaLibrary like this:
MediaLibrary library = new MediaLibrary();
WriteableBitmap wbmp = new WriteableBitmap(image);
MemoryStream ms = new MemoryStream();
Extensions.SaveJpeg(wbmp, ms, wbmp.PixelWidth, wbmp.PixelHeight, 0, 100);
ms.Seek(0, SeekOrigin.Begin);
library.SavePicture(string.Format("Images\\{0}.jpg",imageNumber), ms);
Either way, you can then save the imageNumber back to the IsolatedStorageSettings like this:
settings["PreviousImageNumber"] = imageNumber;
settings.Save();
I had assumed the image used above was set somewhere else in your code. I haven't saved a Canvas to an image before, but some quick searching turned up this blog where an example is given using the WriteableBitmap which indicates you can just replace the image variable with your canvas element:
WriteableBitmap wbmp = new WriteableBitmap(yourCanvas, null);
The article also indicates that the Canvas' background will be ignored and replaced with a black image but that you can overcome this by first adding a rectangle to the Canvas with whatever background you want. Again, I haven't tried this. If this doesn't work you should consider posting another question specifically related to transforming a Canvas to an Image since this is really a separate issue from your original question about saving images.
If you can save the writeable image using CE and want to know how to save the canvas,
then you need to either render canvas to image or if you want to save drawing, then have user draw directly to image, not canvas, by putting blank image (with alpha channel) on canvas, then using mouse move event to add brush marks to image. Thus modifying both display and future input to save method.

Categories