天天看點

RGB資料剪切後儲存為JPG格式檔案的代碼(使用jpeglib)

從一個大的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;
}      

繼續閱讀