bitmap = (Bitmap)Image.FromFile(path)
时间: 2024-04-14 16:31:43 浏览: 16
你这段代码的作用是从指定路径加载一个图像文件,并将其转换为位图格式。这里使用了C#语言的Image类和Bitmap类。
具体来说,`Image.FromFile(path)`会从指定路径加载图像文件,并返回一个Image对象。然后,`(Bitmap)`将该Image对象进行类型转换,转换为Bitmap对象,赋值给变量`bitmap`。
需要注意的是,路径`path`应该是图像文件的完整路径,包括文件名和扩展名。如果文件不存在或者路径不正确,代码可能会抛出异常。因此,在使用这段代码之前,请确保路径是正确的,并且文件存在于指定的路径中。
相关问题
string sourceDir = @"D:\图片类\Holder特殊测试"; string targetDir = @"D:\图片类\压缩图片"; string[] imageFile = Directory.GetFiles(sourceDir, "*.jpg"); // 获取原始图片目录中的所有图片文件 foreach (string imagePath in imageFile)// 遍历每个图片文件,并进行压缩 { using (Bitmap image = new Bitmap(imagePath)) { int targetWidth = 800; int targetHeight =(int)(image.Height * ((float)targetWidth / image.Width)); Bitmap targetImage = new Bitmap(targetWidth, targetHeight); using (Graphics graphics = Graphics.FromImage(targetImage)) { graphics.DrawImage(image, new Rectangle(0, 0, targetWidth, targetHeight)); } var propItem = image.PropertyItems.FirstOrDefault(p => p.Id == 0x0112); if (propItem != null) { image.RemovePropertyItem(propItem.Id); } string targetPath = Path.Combine(targetDir, Path.GetFileName(imagePath)); targetImage.Save(targetPath, ImageFormat.Jpeg); }代码执行完成后图片旋转了180度,怎么让它不旋转
这个问题可能和图片的元数据有关。在你的代码中,已经尝试删除了图片的Orientation属性(0x0112),但似乎没有起作用。
你可以尝试使用其他方法来解决这个问题,如使用ExifLib库来读取和修改图片的元数据。以下是修改图片Orientation属性的示例代码:
```csharp
using ExifLib;
// ...
foreach (string imagePath in imageFile)
{
using (Bitmap image = new Bitmap(imagePath))
{
// 获取原始图片的Orientation属性
int orientation = 0;
using (ExifReader reader = new ExifReader(imagePath))
{
reader.GetTagValue(ExifTags.Orientation, out orientation);
}
int targetWidth = 800;
int targetHeight = (int)(image.Height * ((float)targetWidth / image.Width));
Bitmap targetImage = new Bitmap(targetWidth, targetHeight);
using (Graphics graphics = Graphics.FromImage(targetImage))
{
graphics.DrawImage(image, new Rectangle(0, 0, targetWidth, targetHeight));
}
// 在保存压缩后的图片前,设置Orientation属性为1(表示没有旋转)
using (var ms = new MemoryStream())
{
targetImage.Save(ms, ImageFormat.Jpeg);
ms.Seek(0, SeekOrigin.Begin);
using (var newImage = Image.FromStream(ms))
{
var propItem = newImage.PropertyItems.FirstOrDefault(p => p.Id == 0x0112);
if (propItem != null)
{
propItem.Value[0] = 1;
newImage.SetPropertyItem(propItem);
}
string targetPath = Path.Combine(targetDir, Path.GetFileName(imagePath));
newImage.Save(targetPath, ImageFormat.Jpeg);
}
}
}
}
```
这个示例代码中,使用ExifReader类获取原始图片的Orientation属性,并在保存压缩后的图片前,将该属性设置为1(表示没有旋转)。
C#image转bitmap
可以使用以下代码将 C# 中的 Image 对象转换为 Bitmap 对象:
```csharp
Image image = Image.FromFile("path/to/image.jpg");
Bitmap bitmap = new Bitmap(image);
```
或者,如果你已经有一个 Image 对象,可以直接将其强制转换为 Bitmap 对象:
```csharp
Image image = Image.FromFile("path/to/image.jpg");
Bitmap bitmap = (Bitmap)image;
```