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;
}

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

柳鲲鹏

能给阁下一点帮助,非常荣幸

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值