从一个大的RGBA数据中,剪切部分为RGB格式:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "gh_rgba2jpg.h" #include <jpeglib.h> int clipRgbaToJpgFile(const char *pFileName, const char* pRgbaData, const int nWidth, const int nHeight, const int nClipLeft, const int nClipTop, const int nClipWidth, const int nClipHeight) { char* pClipSource = NULL; char* pClipData = NULL; int pixcelBytes = nClipWidth*nClipHeight*3; int i = 0; int j = 0; pClipSource = malloc(pixcelBytes); if (!pClipSource) { return -1; } //移动到制定位置 pRgbaData += nClipTop * nWidth * 4; pRgbaData += nClipLeft * 4; pClipData = pClipSource; for (i=0; i<nClipHeight; i++) { for (j=0; j<nClipWidth; j++) { //这样性能如何? memcpy(pClipData, pRgbaData, 3); pRgbaData += 4; pClipData += 3; } pRgbaData += (nWidth-nClipWidth) * 4; } rgb2jpg(pFileName, pClipSource, nClipWidth, nClipHeight); //释放资源 free(pClipSource); return 0; }
将剪切后的RGB保存为JPG文件:
int rgb2jpg(char *jpg_file, char *pdata, int width, int height) { int depth = 3; JSAMPROW row_pointer[1]; struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; FILE *outfile; if ((outfile = fopen(jpg_file, "wb")) == NULL) { return -1; } cinfo.err = jpeg_std_error(&jerr); jpeg_create_compress(&cinfo); jpeg_stdio_dest(&cinfo, outfile); cinfo.image_width = width; cinfo.image_height = height; cinfo.input_components = depth; cinfo.in_color_space = JCS_RGB; jpeg_set_defaults(&cinfo); jpeg_set_quality(&cinfo, JPEG_QUALITY, TRUE ); jpeg_start_compress(&cinfo, TRUE); int row_stride = width * depth; while (cinfo.next_scanline < cinfo.image_height) { row_pointer[0] = (JSAMPROW)(pdata + cinfo.next_scanline * row_stride); jpeg_write_scanlines(&cinfo, row_pointer, 1); } jpeg_finish_compress(&cinfo); jpeg_destroy_compress(&cinfo); fclose(outfile); return 0; }