Jpeg2000 with transparency - c#

I'm trying to use Magick.Net to convert a transparent Png to Jpeg2000 format and keep its transparency. The code is rather simple:
using(FileStream source = new FileStream(#"D:\test.png", FileMode.Open))
using(FileStream file = new FileStream(#"D:\test.jp2", FileMode.Create))
using (MagickImage image = new MagickImage(source))
{
image.Format = MagickFormat.Jp2;
image.Write(file);
}
The source image: and result:
As you can see, the image lost its transparency, while both images are 24BPP. What am I missing here?

Related

Convert any image format to JPG

I have a web app that runs on Azure. The user can upload an image and I save that image for them. Now when I receive the image, I have it as byte[]. I would like to save it as JPG to save space. The source image could be anything such as PNG, BMP or JPG.
Is it possible to do so? This needs to run on Azure and I am using WebApps/MVC5/C#.
Thanks for any help.
Get the memorystream and then use System.Drawing
var stream = new MemoryStream(byteArray)
Image img = new Bitmap(stream);
img.Save(#"c:\s\pic.png", System.Drawing.Imaging.ImageFormat.Png);
The last line there where you save the file, you can select the format.
So the answers by #mjwills and Cody was correct. I still thought to put the two methods I exactly needed:
public static Image BitmapToBytes(byte[] image, ImageFormat pFormat)
{
var imageObject = new Bitmap(new MemoryStream(image));
var stream = new MemoryStream();
imageObject.Save(stream, pFormat);
return new Bitmap(stream);
}
Also:
public static byte[] ImgToByteArray(Image img)
{
using (MemoryStream mStream = new MemoryStream())
{
img.Save(mStream, img.RawFormat);
return mStream.ToArray();
}
}
Cheers everyone.

Open multi-page TIF files in a Metro Win 8 application as an image source

It's possible to set a TiF (or TIFF) file in a Metro Application as an Image source very easily...
Image imm = new Image();
imm.Source = new BitmapImage(new Uri(filetiff_path));
The problem is that the content showed in the image is always the first page of the Tif and i am not able to set the content to another pages of the source file.
In WPF app I can do that with the System.Windows.Media.Imaging.TiffBitmapDecoder class that it does not seem to exist in a Metro Win 8 app
Stream imageStreamSource = new FileStream(filetiff_path, FileMode.Open, FileAccess.Read, FileShare.Read);
TiffBitmapDecoder decoder = new TiffBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
BitmapSource bitmapSource = decoder.Frames[indexPage];
Where indexPage is the number of the page that i want to be viewed.
Does anybody know a similar solution?
I don't have any experience with neither TiffBitmapDecoder nor Metro WPF, but I have used a similar thing before in WPF like this:
using (System.Drawing.Image imageFile = System.Drawing.Image.FromFile("temp.tif"))
{
System.Drawing.Imaging.FrameDimension frameDimensions = new System.Drawing.Imaging.FrameDimension(imageFile.FrameDimensionsList[0]);
imageFile.SelectActiveFrame(frameDimensions, indexPage);
using (System.Drawing.Bitmap newImage = new System.Drawing.Bitmap(imageFile.Size.Width, imageFile.Size.Height))
{
using (System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(newImage))
{
gr.Clear(System.Drawing.Color.White);
gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
gr.DrawImage(imageFile, new System.Drawing.Rectangle(new System.Drawing.Point(0, 0), imageFile.Size));
}
//do whatever with the newImage bitmap
}
}
SelectActiveFrame is the point you need there, so you can try that if it also works for you...

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.

Image is not saving after updating, in c# using FileStream or Simple Bitmap

I am working for a utility in desktop application, related to some graphics work.
I have to load small thumbnails and full sized bitmap.I am doing this using this code.
FileStream fs = new FileStream("myphoto.jpg", FileMode.Open);
Image imgPhoto = Image.FromStream(fs);
fs.Close();
PictureBox p = new PictureBox();
p.Name = "p1";
p.Image = imgPhoto;
flowPanel.Controls.Add(p);
//----
FileStream fs = new FileStream("myphoto_thumb.jpg", FileMode.Open);
Image img = Image.FromStream(fs);
fs.Close();
Button b_thumb = new Button();
b_thumb.Name = "thumb1";
b_thumb.BackgroundImage = img;
flowBottom.Controls.Add(b_thumb);
After this, i need to add some effects on image of this picturebox.When i add some effect to main (big) image in picturebox, i also add the same effect in botton background image.When i save this thumbnail image to existing thumbnail image it is saving, but when i save the big image from picturebox on the existing file "myphoto.jpg", it gives me error like FILE IS BEING USED BY ANOTHER PROCESS
//---- Add some Effects to image of Picturebox ---- //
PictureBox tempPic = flowPanel.Controls["p1"];
tempPic.Image.Save("myphoto.jpg",ImageFormat.Jpeg);
I have found many solutions on google and on stackoverflow but could not find helpful.
If any good solution, plz help.
May be its very simple but i have tried more than 10 hours but failed.
You don't close the FileStream you open. I always wrap this kind of stuff in a using construction, so it automatically gets destructed, thus closes:
using (FileStream fs = new FileStream("myphoto.jpg", FileMode.Open)) {
// Do stuff
}
tempPic.Image.Save("myphoto.jpg",ImageFormat.Jpeg);
Try setting your filestream to read only:
fs = New System.IO.FileStream("myphoto.jpg",
IO.FileMode.Open, IO.FileAccess.Read)
This is Microsoft's recommendation, targeted at users who try Image.FromFile and it locks the file: http://support.microsoft.com/kb/309482

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