My project has a picturebox control for loading pictures, it's working fine.
开发者_如何转开发However, some vertical jpg pictures are shown horizontally in Windows Explorer and also in my picturebox control - the same file opened using editors like Photoshop shows a vertical orientation.
How can I get the picture to show with the correct orientation in the picturebox control?
You need to examine the image and extract the orientation information from the exif tags.
The first thing you'll need to do is get an exif reader. There's one written in VB.NET on Code Project for example.
If you load the file into an Image
you will be able to read the EXIF properties from the PropertyItems
(as this C# code demonstrates):
using (Image image = Image.FromFile(imageName))
{
// Non property item properties
this.FileName = imageName;
PixelFormat = image.PixelFormat;
this.Width = image.Size.Width;
this.Height = image.Size.Height;
foreach (PropertyItem pi in image.PropertyItems)
{
EXIFPropertyItem exifpi = new EXIFPropertyItem(pi);
this.propertyItems.Add(exifpi);
}
}
Where EXIFPropertyItem
is a class that converts the PropertyItem
. The PropertyItem
's Id
is the EXIF code (Orientation being 0x0112
).
Then look for the the Orientation property and read it's value. Values 5, 6, 7 and 8 are for portrait (vertical) images, 6 being rotate 90 and 8 being rotate -90 for example.
Once you've got the orientation you can then call the appropriate rotation transformation to display the image in the correct orientation.
When you display an image in a picture box, it will be displayed with its original orientation. Certain image editing applications are able to detect the proper orientation for your images and rotate them automatically, but that would be a fairly difficult algorithm to implement.
However, it's almost trivial to manually rotate an image displayed in a picture box. Just use the System.Drawing.Image.RotateFlip
method that is provided by the .NET Framework, specifying the direction that you want it to be rotated. For example, only one line of code required:
myPictureBox.Image.RotateFlip(RotateFlipType.Rotate180FlipNone)
You could also do it pixel-by-pixel, which might turn out to be faster, relatively speaking, but I doubt it's worth it if you're only rotating one image at a time.
精彩评论