C++存储tga图片

网上有很多关于TGA图片读取的代码,但是还没有相关的存储代码,工作需要,自己写了一个。

工作只要求到写32位,未压缩的,RGBA颜色格式的图片,所以channels没有设置参数,我这里默认是4了

 

_void SaveTGA( const _char *filename, _dword width, _dword height, const _byte *data )

{

// 自定义写数据类型

typedef unsigned char _pixel;

// 打开文件

FILE *savefile = fopen(filename, "wb");

 

// set to {0,0,2,0,0,0,0,0,0,0,0,0} uncompressed tga,我只写未压缩的tga

_pixel type_header[12] =  {0,0,2,0,0,0,0,0,0,0,0,0};

fwrite(  type_header,12*sizeof( _pixel  ),1,savefile );

 

_pixel header[6];

header[0] = width % 256; //图片width 的 lowbyte

header[1] = width / 256; //图片width 的 highbyte

header[2] = height % 256; //图片height 的 lowbyte

header[3] = height / 256; //图片height的 highbyte

header[4] = 32; //位深

header[5] = 8; //每种颜色的位深

 

fwrite( header, 6*sizeof( _pixel ),1,savefile );

 

unsigned int image_size= 4*width*height;

// capy data

_pixel * invert_data = new _pixel [image_size];

memset( invert_data,0,image_size*sizeof( _pixel ) );

for( unsigned int i=0; i<image_size; i++ )

{

invert_data[ i ]  = data[ i ];

}

// Swap red and blue,RGB转为BGR

for ( unsigned int cswap = 0; cswap < image_size; cswap += 4 )

{

_pixel r = invert_data[cswap];

invert_data[cswap] = invert_data[cswap + 2];

invert_data[cswap + 2] = r;

}

 

fwrite( invert_data,image_size*sizeof( _pixel ),1,savefile );

 

delete invert_data;

 

fclose( savefile );

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值