16進RGBからPNG画像に変換
16進RGBからPNG画像に変換
#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#pragma comment(lib, "../pngmake/zlib.lib")
#pragma comment(lib, "../pngmake/libpng.lib")
//#ifdef _MSC_VER //VC++でのコンパイル
#include<io.h>
#include "../pngmake/png.h"
//#else
//#include <png.h>
//#endif
#define WIDTH 256
#define HEIGHT 224
void write_png(const char *file_name, unsigned char **image, int iWidth, int iHeight)
{
FILE *fp;
png_structp png_ptr;
png_infop info_ptr;
fp = fopen(file_name, "wb"); // まずファイルを開きます
png_ptr = png_create_write_struct( // png_ptr構造体を確保・初期化します
PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
info_ptr = png_create_info_struct(png_ptr); // info_ptr構造体を確保・初期化します
png_init_io(png_ptr, fp); // libpngにfpを知らせます
png_set_IHDR(png_ptr, info_ptr, iWidth, iHeight, // IHDRチャンク情報を設定します
8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
png_write_info(png_ptr, info_ptr); // PNGファイルのヘッダを書き込みます
png_write_image(png_ptr, image); // 画像データを書き込みます
png_write_end(png_ptr, info_ptr); // 残りの情報を書き込みます
png_destroy_write_struct(&png_ptr, &info_ptr); // 2つの構造体のメモリを解放します
fclose(fp); // ファイルを閉じます
return;
}
int main()//char *argv[], int argc)
{
char *argv[] = {"", "out.dat", "out.png"};
int argc = 3;
int i;
unsigned char **image; // image[HEIGHT][WIDTH]の形式です
FILE *fp;
int x,y;
char buf[1024];
if(argc!=3){
printf("option err\n");
return -1;
}
image = (unsigned char**)malloc(sizeof(png_bytep)*HEIGHT); // 以下3行は2次元配列を確保します
for(i=0; i<HEIGHT; i++){
image[i] = (unsigned char*)malloc(sizeof(png_byte)*WIDTH*3);
}
fp = fopen(argv[1], "r");
if(fp==NULL){
printf("no file\n");
return -2;
}
x=0;
y=0;
fgets(buf, 1023, fp);
fgets(buf, 1023, fp);
fgets(buf, 1023, fp);
x = y = 0;
while(fgets(buf, 1023, fp)){
int col;
unsigned char R, G, B;
sscanf(buf, "%4x\n", &col);
R = col & 0x001F;
col >>= 5;
G = col & 0x001F;
col >>= 5;
B = col & 0x001F;
image[y][x*3] = R << 3;
image[y][x*3+1] = G << 3;
image[y][x*3+2] = B << 3;
x++;
if(x==WIDTH){
x=0;
y++;
if(y==HEIGHT) break;
}
}
fclose(fp);
printf("%d %d\n", x, y);
write_png(argv[2], image, WIDTH, HEIGHT); // PNGファイルを作成します
system(argv[2]);
printf("write ok\n");
for(i=0; i<HEIGHT; i++) free(image[i]); // 以下2行は2次元配列を解放します
free(image);
printf("end\n");
return 0;
}