C语言实现8bit raw data转换为png

5 篇文章 0 订阅

实现代码如下

fpbigtool.c

#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "svpng.h"

static int g_image_width = 0;
static int g_image_height = 0;

/* 寻找文件路径中最后的 / */
int last_mark(char* str, char mark) {
    int site = 0;
    int count = 0;
    while (site <= strlen(str)) {
        if (str[site++] == mark) {
            count = site;
        }
    }
    return count;
}

/* 寻找文件路径中最后的 . */
int first_mark(char* str, char mark, int num) {
    int count = num;
    while (1) {
        if (str[count++] == mark) {
            break;
        }
    }
    return count;
}

/* 提取文件名, ex: ./bin/image_bin.bin --> image_bin */
int substr(char* file, char* decstr) {
    int lastslash = last_mark(file, '/');
    int firstdot = first_mark(file, '.', lastslash);

    int i = 0;
    int size = firstdot - lastslash - 1;
    for (i = 0; i < size; i++) {
        decstr[i] = file[lastslash++];
    }
    return 0;
}

/* 读取8bit raw data, 存为png */
static int run_8bit_to_png(char* basePath, char* filename) {
    char load_image_bin_path[10240] = {0};
    unsigned char* image_bin = (unsigned char*)malloc(g_image_width * g_image_height);

    snprintf(load_image_bin_path, 10240, "%s/%s", basePath, filename);
    printf("load_image_bin_path=%s\n", load_image_bin_path);

    FILE* fp = fopen(load_image_bin_path, "rb");
    if (fp == NULL) {
        printf("fopen failed : %s, %d\n", __FILE__, __LINE__);
        return 0;
    }

    int read_size = fread(image_bin, 1, g_image_width * g_image_height, fp);
    printf("read_size=%d\n", read_size);
    if (read_size != g_image_width * g_image_height) {
        printf("fread failed : %s, %d\n", __FILE__, __LINE__);
        return 0;
    }
    fclose(fp);

    char png_filename[20240] = {0};
    char save_image_png_path[10240] = {0};
    substr(load_image_bin_path, png_filename);
    snprintf(save_image_png_path, 10240, "%s/%s.png", basePath, png_filename);
    printf("save_image_png_path=%s\n", save_image_png_path);

    FILE* fp_png = fopen(save_image_png_path, "wb");
    unsigned char* rgb = (unsigned char*)malloc(g_image_width * g_image_height * 3);
    unsigned char* p = rgb;
    unsigned int x, y, i = 0;
    /* 所用raw data是8bit,所有r=g=b,其他位深度参考Github */
    for (y = 0; y < g_image_width; y++) {
        for (x = 0; x < g_image_height; x++) {
            *p++ = (unsigned char)image_bin[i]; /* R */
            *p++ = (unsigned char)image_bin[i]; /* G */
            *p++ = (unsigned char)image_bin[i]; /* B */
            i++;
        }
    }

    svpng(fp_png, g_image_width, g_image_height, rgb, 0);
    fclose(fp_png);
    return 0;
}

/* 递归 */
static int run_step(char* basePath) {
    DIR* dir;
    struct dirent* ptr;
    char base[10240];

    dir = opendir(basePath);
    if (dir == NULL) {
        return -1;
    }

    while ((ptr = readdir(dir)) != NULL) {
        if (strcmp(ptr->d_name, ".") == 0 || strcmp(ptr->d_name, "..") == 0) {
            continue;
        } else if (ptr->d_type == 8) {
            run_8bit_to_png(basePath, ptr->d_name);
        } else if (ptr->d_type == 4) {
            snprintf(base, 10240, "%s/%s", basePath, ptr->d_name);
            run_step(base);
        } else {
            break;
        }
    }

    closedir(dir);
    return 0;
}

static void help() {
    printf("#***********************************************#\n");
    printf("#***********************************************#\n");
    printf("#****               FpBigTool               ****#\n");
    printf("#***********************************************#\n");
    printf("#***********************************************#\n");
    printf("#**       ex: ./fpbigtool 108 21 ./image      **#\n");
    printf("#***********************************************#\n");
}

int main(int argc, char const* argv[]) {
    if (argc < 4) {
        printf("ERROR! too few parameters!\n");
        help();
        return 0;
    }

    g_image_width = atoi(argv[1]);
    g_image_height = atoi(argv[2]);
    printf("image_width=%d image_height=%d image_path=%s\n", g_image_width, g_image_height,
           argv[3]);

    run_step((char*)argv[3]);
    return 0;
}

svpng.h

/*
Copyright (C) 2017 Milo Yip. All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

* Neither the name of pngout nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/*! \file
    \brief      svpng() is a minimalistic C function for saving RGB/RGBA image into uncompressed PNG.
    \author     Milo Yip
    \version    0.1.1
    \copyright  MIT license
    \sa         http://github.com/miloyip/svpng
*/

#ifndef SVPNG_INC_
#define SVPNG_INC_

/*! \def SVPNG_LINKAGE
    \brief User customizable linkage for svpng() function.
    By default this macro is empty.
    User may define this macro as static for static linkage, 
    and/or inline in C99/C++, etc.
*/
#ifndef SVPNG_LINKAGE
#define SVPNG_LINKAGE
#endif

/*! \def SVPNG_OUTPUT
    \brief User customizable output stream.
    By default, it uses C file descriptor and fputc() to output bytes.
    In C++, for example, user may use std::ostream or std::vector instead.
*/
#ifndef SVPNG_OUTPUT
#include <stdio.h>
#define SVPNG_OUTPUT FILE* fp
#endif

/*! \def SVPNG_PUT
    \brief Write a byte
*/
#ifndef SVPNG_PUT
#define SVPNG_PUT(u) fputc(u, fp)
#endif


/*!
    \brief Save a RGB/RGBA image in PNG format.
    \param SVPNG_OUTPUT Output stream (by default using file descriptor).
    \param w Width of the image. (<16383)
    \param h Height of the image.
    \param img Image pixel data in 24-bit RGB or 32-bit RGBA format.
    \param alpha Whether the image contains alpha channel.
*/
SVPNG_LINKAGE void svpng(SVPNG_OUTPUT, unsigned w, unsigned h, const unsigned char* img, int alpha) {
    static const unsigned t[] = { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c, 
    /* CRC32 Table */    0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c };
    unsigned a = 1, b = 0, c, p = w * (alpha ? 4 : 3) + 1, x, y, i;   /* ADLER-a, ADLER-b, CRC, pitch */
#define SVPNG_U8A(ua, l) for (i = 0; i < l; i++) SVPNG_PUT((ua)[i]);
#define SVPNG_U32(u) do { SVPNG_PUT((u) >> 24); SVPNG_PUT(((u) >> 16) & 255); SVPNG_PUT(((u) >> 8) & 255); SVPNG_PUT((u) & 255); } while(0)
#define SVPNG_U8C(u) do { SVPNG_PUT(u); c ^= (u); c = (c >> 4) ^ t[c & 15]; c = (c >> 4) ^ t[c & 15]; } while(0)
#define SVPNG_U8AC(ua, l) for (i = 0; i < l; i++) SVPNG_U8C((ua)[i])
#define SVPNG_U16LC(u) do { SVPNG_U8C((u) & 255); SVPNG_U8C(((u) >> 8) & 255); } while(0)
#define SVPNG_U32C(u) do { SVPNG_U8C((u) >> 24); SVPNG_U8C(((u) >> 16) & 255); SVPNG_U8C(((u) >> 8) & 255); SVPNG_U8C((u) & 255); } while(0)
#define SVPNG_U8ADLER(u) do { SVPNG_U8C(u); a = (a + (u)) % 65521; b = (b + a) % 65521; } while(0)
#define SVPNG_BEGIN(s, l) do { SVPNG_U32(l); c = ~0U; SVPNG_U8AC(s, 4); } while(0)
#define SVPNG_END() SVPNG_U32(~c)
    SVPNG_U8A("\x89PNG\r\n\32\n", 8);           /* Magic */
    SVPNG_BEGIN("IHDR", 13);                    /* IHDR chunk { */
    SVPNG_U32C(w); SVPNG_U32C(h);               /*   Width & Height (8 bytes) */
    SVPNG_U8C(8); SVPNG_U8C(alpha ? 6 : 2);     /*   Depth=8, Color=True color with/without alpha (2 bytes) */
    SVPNG_U8AC("\0\0\0", 3);                    /*   Compression=Deflate, Filter=No, Interlace=No (3 bytes) */
    SVPNG_END();                                /* } */
    SVPNG_BEGIN("IDAT", 2 + h * (5 + p) + 4);   /* IDAT chunk { */
    SVPNG_U8AC("\x78\1", 2);                    /*   Deflate block begin (2 bytes) */
    for (y = 0; y < h; y++) {                   /*   Each horizontal line makes a block for simplicity */
        SVPNG_U8C(y == h - 1);                  /*   1 for the last block, 0 for others (1 byte) */
        SVPNG_U16LC(p); SVPNG_U16LC(~p);        /*   Size of block in little endian and its 1's complement (4 bytes) */
        SVPNG_U8ADLER(0);                       /*   No filter prefix (1 byte) */
        for (x = 0; x < p - 1; x++, img++)
            SVPNG_U8ADLER(*img);                /*   Image pixel data */
    }
    SVPNG_U32C((b << 16) | a);                  /*   Deflate block end with adler (4 bytes) */
    SVPNG_END();                                /* } */
    SVPNG_BEGIN("IEND", 0); SVPNG_END();        /* IEND chunk {} */
}

#endif /* SVPNG_INC_ */

PNG转换头头文件转自: Github svpng
提取文件名的参考自: 提取文件名小程序
完整代码下载:FpBigTool-Linux 执行包中的build_android.sh编译为Android下可执行文件,执行build_linux.sh编译Linux下的可执行文件

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值