Подтвердить что ты не робот

Получить ImageFormat из расширения файла

Есть ли быстрый способ получить объект ImageFormat, связанный с определенным расширением файла? Я ищу быстрее, чем сравнение строк для каждого формата.

4b9b3361

Ответ 1

Вот какой-то старый код, который я нашел, который должен сделать трюк:

 string InputSource = "mypic.png";
 System.Drawing.Image imgInput = System.Drawing.Image.FromFile(InputSource);
 Graphics gInput = Graphics.fromimage(imgInput);
 Imaging.ImageFormat thisFormat = imgInput.RawFormat;

Это требует фактического открытия и тестирования изображения - расширение файла игнорируется. Предполагая, что вы все равно открываете файл, это гораздо более надежное, чем доверенное расширение файла.

Если вы не открываете файлы, нет ничего "быстрее" (в смысле производительности), чем сравнение строк, - конечно, не вызывая в ОС, чтобы получать сопоставления расширений файлов.

Ответ 2

private static ImageFormat GetImageFormat(string fileName)
{
    string extension = Path.GetExtension(fileName);
    if (string.IsNullOrEmpty(extension))
        throw new ArgumentException(
            string.Format("Unable to determine file extension for fileName: {0}", fileName));

    switch (extension.ToLower())
    {
        case @".bmp":
            return ImageFormat.Bmp;

        case @".gif":
            return ImageFormat.Gif;

        case @".ico":
            return ImageFormat.Icon;

        case @".jpg":
        case @".jpeg":
            return ImageFormat.Jpeg;

        case @".png":
            return ImageFormat.Png;

        case @".tif":
        case @".tiff":
            return ImageFormat.Tiff;

        case @".wmf":
            return ImageFormat.Wmf;

        default:
            throw new NotImplementedException();
    }
}

Ответ 3

    private static ImageFormat GetImageFormat(string format)
    {
        ImageFormat imageFormat = null;

        try
        {
            var imageFormatConverter = new ImageFormatConverter();
            imageFormat = (ImageFormat)imageFormatConverter.ConvertFromString(format);
        }
        catch (Exception)
        {

            throw;
        }

        return imageFormat;
    }