I'm trying to process the typical 16 megapixel images from a modern camera. Picking a random image, both the file system and my image editing software says the image is 4608 x 3456. When I load the image in C# (VS2013 .Net 4.5) using either new Bitmap(filename) or Image.FromFile(filename), I get an image successfully loaded. However, the resulting image has a size of 1613 x 1210. Now, in some cases I want to create custom size thumbnails, and this will work ok. However, I have another need where I detect "non normal" orientations and I simply want to flip/rotate for display, then save.
Saving these images (without any adjustments, just load and save) creates a valid image on disk. However, both the file system AND my image tool says the size is 1613 x 1210.
How do I load the full size image and preserve all info back to disk? Any ideas as to what I'm doing wrong? I just want to rotate the image where needed, I don't want to shrink it!
Here's a snippet of what I tried, as promised in a comment below:
Bitmap bm = new Bitmap(fileName);
Image jpg = Image.FromFile(fileName);
jpg.Save("e:\\test.jpg");
bm.Save("e:\\test2.jpg");
Both files are smaller than their original size, and match the width and height the debugger shows for both in-memory images.
Per a suggested answer, I tried this code but saw no difference in the results:
long width = 0;
long height = 0;
byte[] imageBytes = File.ReadAllBytes(fileName);
using (MemoryStream ms = new MemoryStream(imageBytes))
{
Image jpg3 = Image.FromStream(ms);
width = jpg3.Width;
height = jpg3.Height;
jpg3.Save("e:\\test3.jpg",System.Drawing.Imaging.ImageFormat.Jpeg);
}
Thanks in advance.
[EDIT]
User Error from a followup post:
While it's true I do have a 4608x3456 size image of the very picture I
am trying to load, I selected the wrong directory in my OpenFileDialog
and was actually selected a, you guessed it, 1613 x 1210 version of
this image. The code WAS loading the full thing, the silly operator
(me) was gumming it up.
Before I post, I'll try the full-size image ... yeah, it works fine.
Can you show your program code?
I downloaded 5169x3423 size sample image.
Load this image using program and when i restored it, original and new image are same.
I load image file to byte array and save it to Bitmap.
private Image LoadImage()
{
OpenFileDialog openFile = new OpenFileDialog();
openFile.ShowDialog();
byte[] byteImage = File.ReadAllBytes(openFile.FileName);
Image myImage;
using (var ms = new MemoryStream(byteImage))
{
myImage = Image.FromStream(ms);
}
return myImage;
}
private void SaveImage(Image myImage)
{
Bitmap bmp = new Bitmap(myImage);
// Temp save location
bmp.Save("c:\\test\\myImage.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
}
Related
I am attempting to past an image onto a pdf using Telerik in C#. The following code adds the image, but it's upside down. Telerik seems to paste it upside down no matter what rotation type I use on RotateFlip. The image should display UnUnU, but it's upside down and displays NuNuN. I added the image into the below code in base64.
How can I flip the image?
using (MemoryStream ms = new MemoryStream((byte[])Convert.FromBase64String("/9j/4AAQSkZJRgABAQAASABIAAD/4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAR6ADAAQAAAABAAAAFAAAAAD/7QA4UGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAAA4QklNBCUAAAAAABDUHYzZjwCyBOmACZjs+EJ+/8AAEQgAFABHAwERAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/bAEMAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB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Y);
tmpimage.Save(ms, ImageFormat.Png);
var image = page.Content.AddImage(new ImageSource(ms));
}
Thanks for any help!!
I have a problem with transparency in the .png image when inserting to Catia V5 CATDrawing document. Something changes in the image after saving with System.Drawing.Image.Save(). If a newly saved image is opened with Paint.NET image is transparent and everything seems fine, but when inserted in CATDrawing image has no transparency. I can't find out what is changed in the image to cause this loss of transparency.
I'm rotating image that's why I need to save it. This is the code I'm using to rotate and save images.
Bitmap image1 = (Bitmap)Image.FromFile(sImagePath1, true);
image1.RotateFlip(RotateFlipType.Rotate90FlipNone);
image1.MakeTransparent();
image1.Save(sImagePath2, ImageFormat.Png);
I have also tried and failed with NuGet package Magick.NET-Q16-AnyCPU
using (MagickImage mimg = new(sImagePath1))
{
mimg.Rotate(90);
mimg.Write(sImagePath2);
}
and with save as stream
Bitmap image1 = (Bitmap)Image.FromFile(sImagePath1, true);
image1.RotateFlip(RotateFlipType.Rotate90FlipNone);
using (FileStream outputFileStream = new(sImagePath2, FileMode.Create))
{
var stream = new MemoryStream();
image1.Save(stream, ImageFormat.Png);
stream.Position = 0;
stream.CopyTo(outputFileStream);
}
Question: is there any other solution to rotate and save images via C# code?
Hi I'm afraid that Catia V5 can't import png with transparency. Try it yourself if manually putting the image into drawing keeps transparency. I Tried it but in my case it doesn't work.
In Catia you can rotate the picture manually but not trough api.
You can try vector image instead of bitmap, but this is just my guess.
If I copy a region from Photoshop in RGB 8 bits the Clipboard.GetImage() has a black and white image, but if I change it to an indexed mode (256) GetImage returns a colored image.
I've also tried with the GetDataObject method, but with same results. It seems the image format is memoryBMP but in RGB/8 format so I can't get the full colored image.
How to retrieve color image from Photoshop clipboard format back into my C# app?
This is the code I'm using. The image is saved, but..
If I copy pixels from an image in Photoshop mode RGB/8 it save as b/w.
If mode is index (256 colors) it saves color.
The image format in data is of type :
[ImageFormat: b96b3caa-0728-11d3-9d7b-0000f81ef32e] MemoryBMP
Following is my C# code...
IDataObject data = Clipboard.GetDataObject();
if (data.GetDataPresent(DataFormats.Dib))
{
Bitmap image = (System.Drawing.Image)data.GetData(DataFormats.Dib, false) as Bitmap;
var encoder = ImageCodecInfo.GetImageEncoders().First(c => c.FormatID == ImageFormat.Jpeg.Guid);
var encParams = new EncoderParameters(1);
encParams.Param[0] = new EncoderParameter(Encoder.ColorDepth, 24L);
image.Save("encode.jpg", encoder, encParams);
}
If you're trying to just select a rectangle area in Photoshop (or any image program, like Paint etc) then paste that into your app (via get from Clipboard)...
Try it like this :
//# Get copied data (image) from clipboard
IDataObject data = Clipboard.GetDataObject();
if (data.GetDataPresent(DataFormats.Dib))
{
//# Make into C# bitmap
Bitmap image = (data.GetData(DataFormats.Bitmap,true) as Bitmap);
//# Show in some PictureBox
//pbx.Image = image;
//# Save to disk
image.Save("c:/test//encode_test1.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
}
Compile and run your app (its window should be open).
In Photoshop.. open an image and select/copy an area.
In your app, get the image brought in (I used keypress to run function of above code).
Find the JPG file at C:\ drive inside the test folder.
If you created aPictureBox object you can even view "selected area" image within your app.
Right now I have a form with a PictureBox on the form. I'm using two partially transparent images and trying to put one on top of the other.
sideMenuWide = rounded rectangle with transparent background (.png) [Bottom image]
labelPointer = triangle with transparent background (.png) [Top image]
Here is my approach:
// METHOD #1 //
Image img1 = Image.FromFile(#"C:\sideMenuWide.png");
Image img2 = Image.FromFile(#"C:\labelPointer.png");
picBox.Image = CombineImages(img1, img2);
// METHOD #2 //
Image imgA = RBS.Properties.Resources.sideMenuWide;
Image imgB = RBS.Properties.Resources.labelPointer;
picBox.Image = CombineImages(imgA, imgB);
And the CombineImage function: (I did not write this function, only modified)
public static Bitmap CombineImages(Image imgA, Image imgB)
{
//a holder for the result (By default, use the first image as the main size)
Bitmap result = new Bitmap(imgA.Size.Width, imgA.Size.Height);
//use a graphics object to draw the resized image into the bitmap
using (Graphics graphics = Graphics.FromImage(result))
{
//set the resize quality modes to high quality
graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//draw the images into the target bitmap
graphics.DrawImage(imgA, 0, 0, imgA.Width, imgA.Height);
graphics.DrawImage(imgB, 100, 70, imgB.Width, imgB.Height);
}
return result;
}
Method #1 DOES work how I want it to, displays imgB perfectly on top of imgA.
Method #2 however shows imgA just fine but imgB is really faint.
Any ideas on how to overcome this? I would like to be able to do this using Resources instead of having to pull from a file.
If the files work when loaded, but the resources don't, then it sounds like the resx build process or the ResourceManager is doing something undesirable. I'd try embedding the files and reading them directly from a stream rather than relying on the ResourceManager to do it for you.
In your Solution Explorer, Add Existing File to add the file to your project. Get properties on the added file and set it to Embedded Resource=. (Don't add it to a resx file)
In your code, you can now get a stream containing the file's data:
Stream instream = Assembly.GetExecutingAssembly().
GetManifestResourceStream("RBS.labelPointer.png"));
(Hint: The compiler generates an obtuse name for the embedded resource, so after adding the files you can add temporary code to call Assembly.GetExecutingAssembly().GetManifestResourceNames() to get a list of them all and find the file you're interested in)
Load your bitmap/image from the stream:
Image img2 = new Bitmap(inStream);
I was wondering if someone can direct me or guide me in order to use a .gif image and convert it into a .bmp strip image file.
First, you need to get the gif's size. Then you need to find out how many frames there are.
After that you need to create a new image with Height = original height, and Width = Frames * Gif Width.
Then you must paste the original Gif's frames into the strip like so: Frame N starts at pixel N*Width.
That is if you're making a horizontal strip.
And here is the complete code for a console application:
using System.Drawing;
using System.Drawing.Imaging;
foreach (var arg in args)
{
Image gif = Image.FromFile(arg);
FrameDimension dim = new FrameDimension(gif.FrameDimensionsList[0]);
int frames = gif.GetFrameCount(dim);
Bitmap resultingImage = new Bitmap(gif.Width * frames, gif.Height);
for (int i = 0; i < frames; i++)
{
gif.SelectActiveFrame(dim, i);
Rectangle destRegion = new Rectangle(gif.Width * i, 0, gif.Width, gif.Height);
Rectangle srcRegion = new Rectangle(0, 0, gif.Width, gif.Height);
using (Graphics grD = Graphics.FromImage(resultingImage))
{
grD.DrawImage(gif, destRegion, srcRegion, GraphicsUnit.Pixel);
}
}
resultingImage.Save("res.png", ImageFormat.Png);
}
The resulting image is saved in the compiled console app binary file directory under the name res.png. You can make the app save the resulting image right where the source file is, ask whether to make a horizontal or vertical strip, etc.
Making an image strip can be easily done with Photoshop (you can get a free trial version, or Elements)
Open .gif - Photoshop will open each frame as a layer
Resize canvas to (height of the gif * layers) pixels
Remove all frame information, keep layers
Select last layer, and move it to very bottom
Select all layers and click 'Distribute vertical centers'. Now you have a perfectly arranged strip.
If you are using Photoshop, you can just export as BMP. Thats it.
The method what works for sure is:
Download an install Easy GIF Animator
Open tour gif with it and export the frames to separate files
Download and install any program which can create the layers (eg. Photoshop CS3 Little)
Create a new file width as your picture; Height = Height of Your pic. X number of pictures
Copy each pic. as a layers in to Your new file and move them one after the other.
Save it as a .png file
Download an install iPAQ 31x Image Explorer
Open Your .png in it
Save it as aRGB file (normal BMP may don't work)
DONE!!
Maybe it's not the easiest method but it gives the possibility of precise editing and allows you to make strips of icons that are on a transparent background (but not limited to icons)
Just load .gif in Bitmap and save it in .bmp. If you want to export the frames of .gif I have no idea how to do this. You can have look at this www.eggheadcafe.com/articles/stripimagefromanimatedgif.asp, it seems to be what what you're looking for.