从JPEG读取EXIF-Thumbnail [英] Read EXIF-Thumbnail from JPEG

查看:392
本文介绍了从JPEG读取EXIF-Thumbnail的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一种高性能的方法来从jpg文件中提取缩略图而无需读取整个文件。

I need a performant way to extract a thumbnail from a jpg-file without reading the whole file.

我写了这个方法,应该可以正常工作 - 但事实并非如此。无法读取新文件。我的错误在哪里?

I wrote this method, which should work well - but it doesn't. The new file can not be read. Where is my mistake?

public static System.Drawing.Image GetThumbnail(string Image)
{
    try
    {
        List<byte> image = new List<byte>();
        byte[] _startToken = new byte[2] { 0xFF, 0xD8 }; //JPEG Start
        byte[] _endToken = new byte[2] { 0xFF, 0xD9 }; //JPEG End
        byte[] buff = new byte[2];
        FileStream fs = new FileStream(Image, FileMode.Open, FileAccess.Read);
        BinaryReader br = new BinaryReader(fs);
        while (br.BaseStream.Position < br.BaseStream.Length)
        {
            byte bCurrent = br.ReadByte();
            buff[0] = buff[1];
            buff[1] = bCurrent;
            if (Enumerable.SequenceEqual(buff, _startToken))
            {
                image.Clear();
                image.AddRange(buff);
            };
            if (Enumerable.SequenceEqual(buff, _endToken))
            {
                break;
            };
            image.Add(bCurrent);
        }
        return (Bitmap)((new ImageConverter()).ConvertFrom(image.ToArray()));
    }
    catch
    {
        return null;
    }
}


推荐答案

整个JPEG文件在FFD8 - FFD9字节内,而不仅仅是缩略图,所以你在那里的代码将复制整个文件。如果你检查image.jpg和thumbnail.jpg的确切大小,你应该看到这个。

The whole JPEG file is inside the FFD8 - FFD9 bytes, not just the thumbnail so the code you've got there would copy the whole file. If you check the exact sizes of image.jpg and thumbnail.jpg you should see this.

但是,因为 Image.Clear 你丢失了第一个字节,然后中断会导致你输掉最后一个字节。

However, because of the Image.Clear you are losing the first byte and then the break causes you to lose the last one.

您需要根据JPEG结构实际解析文件,以便可靠地提取缩略图。我没有使用它,但你可能会发现采用现有的库。

You will need to actually parse the file according to the JPEG structure to reliably extract the thumbnail. I haven't used it but you may find it easier to adopt an existing library.

这篇关于从JPEG读取EXIF-Thumbnail的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆