在特定的应用场景下,有时候我们只是想获取图片的宽高,

但不想通过解码图片才取得这个信息。

预先知道图片的宽高信息,进而提速图片加载,预处理等相关操作以提升体验。

在stackoverflow有一篇相关讨论。

Get Image size WITHOUT loading image into memory
http://stackoverflow.com/questions/15800704/python-get-image-size-without-loading-image-into-memory/

不加图片到内存,而取得图像的大小。

这个技巧具有一定的实用价值,博主据此进行了相应的编码。

实现了 常用图片格式(png,jpeg,ico,bmp,gif) 不采用第三方解码库,解析得到图像宽高的函数get_image_size_without_decode_image。

bool get_image_size_without_decode_image(const char* file_path, int*width, int*height);

完整代码:

#include <stdio.h>
#include <sys/stat.h> 

unsigned long byteswap_ulong(unsigned long i)
{
    unsigned int j;
    j = (i << );
    j += (i << ) & 0x00FF0000;
    j += (i >> ) & 0x0000FF00;
    j += (i >> );
    return j;
} 

inline int Abs(int x) {
    )) - (x >> );
}

unsigned short byteswap_ushort(unsigned short i)
{
    unsigned short j;
    j = (i << );
    j += (i >> );
    return j;
}

// Get Image size WITHOUT loading image into memory
// ref: http://stackoverflow.com/questions/15800704/python-get-image-size-without-loading-image-into-memory/
// 博客: http://tntmonks.cnblogs.com/
// 邮箱: gaozhihan@vip.qq.com
bool get_image_size_without_decode_image(const char* file_path, int*width, int*height)
{
    bool has_image_size = false;
    *height = -;
    *width = -;
    ;
    FILE * fp = fopen(file_path, "rb");
    if (fp == NULL)
        return has_image_size;
    struct stat st;
    ];
    )
    {
        fclose(fp);
        return has_image_size;
    }
    else
    {
        file_size = st.st_size;
    }
    , , fp) < )
    {
        fclose(fp);
        return has_image_size;
    }
    char* png_signature = "\211PNG\r\n\032\n";
    unsigned ] = { 'I', 'H', 'D', 'R' };
    char* gif87_signature = "GIF87a";
    char* gif89_signature = "GIF89a";
    char* jpeg_signature = "\377\330";
    char* bmp_signature = "BM";
    ) && (memcmp(sigBuf, gif87_signature, strlen(gif87_signature)) ==  || memcmp(sigBuf, gif89_signature, strlen(gif89_signature)) == ))
    {
        // image type: gif
        unsigned );
        *width = size_info[];
        *height = size_info[];
        has_image_size = true;
    }
    ) && (memcmp(sigBuf, png_signature, strlen(png_signature)) ==  && memcmp(sigBuf + , ihdr_signature, strlen(ihdr_signature)) == ))
    {
        // image type:   png
        unsigned );
        *width = byteswap_ulong(size_info[]);
        *height = byteswap_ulong(size_info[]);
        has_image_size = true;
    }
    ) && (memcmp(sigBuf, png_signature, strlen(png_signature)) == ))
    {
        // image type: old png
        unsigned );
        *width = byteswap_ulong(size_info[]);
        *height = byteswap_ulong(size_info[]);
        has_image_size = true;
    }
    ) && (memcmp(sigBuf, jpeg_signature, strlen(jpeg_signature)) == ))
    {
        // image type: jpeg
        fseek(fp, , SEEK_SET);
        ;
        fread(&sigBuf, , , fp);
        fread(&b, , , fp);
        ;
        ;
        while (b && ((unsigned char)b & 0xff) != 0xDA) {
            while (((unsigned char)b & 0xff) != 0xFF)
            {
                fread(&b, , , fp);
            }
            while (((unsigned char)b & 0xff) == 0xFF) {
                fread(&b, , , fp);
            }
            if (((unsigned char)b & 0xff) >= 0xC0 && ((unsigned char)b & 0xff) <= 0xC3)
            {
                fread(&sigBuf, , , fp);
                fread(&sigBuf, , , fp);
                unsigned short* size_info = (unsigned short*)(sigBuf);
                h = byteswap_ushort(size_info[]);
                w = byteswap_ushort(size_info[]);
            }
            else
            {
                unsigned ;
                fread(&chunk_size, , , fp);
                , SEEK_CUR) != )
                    break;
            }
            fread(&b, , , fp);
        }
         && h != -)
        {
            *width = w;
            *height = h;
        }
        has_image_size = true;
    }
    ) && (memcmp(sigBuf, bmp_signature, strlen(bmp_signature)) == ))
    {
        // image type: bmp
        unsigned ));
        )
        {
            unsigned );
            *width = size_info[];
            *height = size_info[];
        }
        )
        {
            unsigned );
            *width = size_info[];
            *height = Abs((size_info[]));
        }
        has_image_size = true;
    }
    )
    {
        // image type: ico
        fseek(fp, , SEEK_SET);
        unsigned ;
        unsigned ;
        fread(&reserved, , , fp);
        fread(&format, , , fp);
         && format == )
        {
            unsigned ;
            fread(&num, , , fp);
            )
            {
                printf("ico 包含多个图片");
            }
            else
            {
                , h = ;
                fread(&w, , , fp);
                fread(&h, , , fp);
                *width = int((unsigned char)w & 0xff);
                *height = int((unsigned char)h & 0xff);
            }
        }
        has_image_size = true;
    }
    if (fp != NULL)
        fclose(fp);
    return has_image_size;
}

调用方法:

const char* file_path = "d:\\test.png";

int h, w;
get_image_size_without_decode_image(file_path , &w, &h);

传入图片的位置,输出对应的宽高,高和宽 为-1时,就是解析失败了。

代码比较简单,不多注释了。

若有其他相关问题或者需求可以邮件联系俺探讨。

邮箱地址是: 
gaozhihan@vip.qq.com

不用第三方解码码取得图片宽高 附完整C++算法实现代码的更多相关文章

  1. 不用第三方解码库取得图片宽高 附完整C++算法实现代码

    在特定的应用场景下,有时候我们只是想获取图片的宽高, 但不想通过解码图片才取得这个信息. 预先知道图片的宽高信息,进而提速图片加载,预处理等相关操作以提升体验. 在stackoverflow有一篇相关 ...

  2. JS快速获取图片宽高的方法

    快速获取图片的宽高其实是为了预先做好排版样式布局做准备,通过快速获取图片宽高的方法比onload方法要节省很多时间,甚至一分钟以上都有可能,并且这种方法适用主流浏览器包括IE低版本浏览器. 我们一步一 ...

  3. 转载:JS快速获取图片宽高的方法

    快速获取图片的宽高其实是为了预先做好排版样式布局做准备,通过快速获取图片宽高的方法比onload方法要节省很多时间,甚至一分钟以上都有可能,并且这种方法适用主流浏览器包括IE低版本浏览器. 我们一步一 ...

  4. JS实现图片宽高的等比缩放

    关于图片宽高的等比缩放,其实需求就是让图片自适应父容器的宽高,并且是等比缩放图片,使图片不变形. 例如,需要实现如下的效果: 要实现上面的效果,需要知道图片的宽高,父容器的宽高,然后计算缩放后的宽高. ...

  5. php 图片上传的公共方法(按图片宽高缩放或原图)

    写的用于图片上传的公共方法类调用方法: $upload_name='pic';$type = 'logo_val';$file_name = 'logo_' . $user_id .create_st ...

  6. css3圆形头像(当图片宽高不相等时)

    1.图片宽高相等,width:300px: height:300px; 把他变成宽高100px的圆形头像 img{width:100px; height:100px; border-radius:50 ...

  7. js不需要知道图片宽高的懒加载方法(经过实际测试,不加宽高仍然是无法正常加载的,设置height:auto,height:100%,仍然显示高度为0)

    js不需要知道图片宽高的懒加载方法 懒加载是如何实现的? - 简书https://www.jianshu.com/p/e86c61468285找到一个不需要知道图片宽高的懒加载方法了(经过实际测试,不 ...

  8. css+background实现 图片宽高自适应,拉伸裁剪不变形

    图片宽高不固定 ,一样实现自适应,拉伸裁剪不变形,适应各大兼容性.  下面咱们在网上找两张宽高不一样的照片:     No.1                                      ...

  9. 写个js动态调整图片宽高 (原创)

    <body style="TEXT-ALIGN: center;"> <div id="testID" style="backgro ...

随机推荐

  1. myeclipse无法导入项目

    MyEclipse无法导入Java项目时常遇到的两种情况: 1.Some projects cannot be imported because they already exist in the w ...

  2. 添加用户useradd,给用户设置修改密码passwd,修改用户信息usermod,修改用户密码状态chage,删除用户userdel,查询用户及组id,切换用户su,查看当前环境变量env

    useradd 用户名 passwd 用户名,给指定用户设密码 passwd给当前用户设密码 添加一个用户系统会自动在以下文件或目录创建对应用户信息: [root@localhost ~]# grep ...

  3. linux命令(shell)

    1.cat查看一个文件,linux默认bash 2.echo回显命令 3.ls 4.history历史记录,查看使用过的命令 5.根目录下文件目录 6.bin目录下内容多为应用程序和命令 7.boot ...

  4. 理解new构造函数和apply以及call

    今天在看设计模式的时候,遇到一些挺低级的东西,搞不懂,顾查阅资料整理记录一番. 先了解一下new构造函数的过程: function func(){ console.log('do'); } var f ...

  5. Saltstack的安装和配置

    1.安装salt 因为系统自带的yum源不支持saltstack安装包的支持,所以需要安装第三方yum源(epel) # yum -y install epel-release salt分为主服务器( ...

  6. [解决方案]WebAPI+SwaggerUI部署服务器后,访问一直报错的问题

    项目的背景:制作一批接口用来给前台app或者网站提供服务,因为WebApi是最近几年来比较流行和新颖的开发接口的方式,而且又属于轻型应用,所以选用它 部署的过程:建立了WebAPI项目并使用Swagg ...

  7. [编织消息框架][JAVA核心技术]动态代理应用3

    我们先使用懒处理实现提取接口类上的元信息: public abstract class QRpcFactory { public static <T> T loadProxy(Class& ...

  8. jamup与gb2i组合

    软件一定要开嗓单效果器,最好不要关闭中断软件/声音,每次有重新检测电流必须会有嗓音,最好用ipad ,不然会烦死人.默认delay太长,在DLY面板修改 gb2i 效果还行,他的价值重在使用,让新人使 ...

  9. 日语编程语言"抚子" - 第三版特色初探

    原址: https://zhuanlan.zhihu.com/p/30800689 原文: 日语编程语言"抚子" - 第三版特色初探 它山之石可以攻玉. 学习其他的母语编程语言, ...

  10. MySQL数据库学习: 01 —— 数据库的概述

    壹 概述 一 了解SQL 1.1 数据库基础 1.1.1 什么是数据库 数据库(database)保存有组织的数据的容器(通常是一个文件或一组文件). 易混淆:人们常常用“数据库”这个词语来代表他们使 ...