简体   繁体   English

在 C# 中将文件转换为位图

[英]Convert files to bitmap in C#

I write this code to read files from folder in directory(@"D:\\\\test\\\\ISIC_2020_Training_JPEG") , then convert each file to bitmap in c#我编写此代码以从目录中的文件夹读取文件directory(@"D:\\\\test\\\\ISIC_2020_Training_JPEG") ,然后将每个文件转换为 c# 中的位图

foreach (string img in Directory.EnumerateFiles(@"D:\\test\\ISIC_2020_Training_JPEG"))
    Bitmap  bmp = new Bitmap(img);

But there is an error that appears in the last line, which is:但是最后一行出现了一个错误,就是:

Out of memory Exception内存不足异常

what is the problem in this code?这段代码有什么问题?

I suppose that you have all jpeg files on provided directory, you could load image file in memory stream and check if everything okay when you load image in memory stream.我想您在提供的目录中拥有所有 jpeg 文件,您可以在内存流中加载图像文件,并在将图像加载到内存流中时检查一切是否正常。

foreach (string imgPath in Directory.GetFiles(@"D:\test\ISIC_2020_Training_JPEG"))
{
    Bitmap  bmp;
    byte[] buff = System.IO.File.ReadAllBytes(imgPath);
    using(System.IO.MemoryStream ms = new System.IO.MemoryStream(buff))
    {
        bmp = new Bitmap(ms);
    }
}
    

Probably the best approach would be to stream the image files so if there's a large file it won't hog up too much memory.可能最好的方法是流式传输图像文件,这样如果文件很大,它就不会占用太多内存。 Then check if the file is in the correct format before trying to convert to a Bitmap , hopefully this helps:然后在尝试转换为Bitmap之前检查文件的格式是否正确,希望这会有所帮助:

Bitmap bitmap;
Image image;
foreach (string imgFile in Directory.EnumerateFiles(@"D:\test\ISIC_2020_Training_JPEG"))
{
    using (Stream bmpStream = File.Open(imgFile, FileMode.Open))
    {
        image = Image.FromStream(bmpStream);
        if (ImageFormat.Jpeg.Equals(image.RawFormat)) // Check it's the correct format
        {
            bitmap = new Bitmap(image);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM