使用jpeglib直接把NV12转为jpeg文件的代码

本文介绍了一种从NV12格式转换为JPEG的方法,包括C语言源代码实现及编译步骤。通过该方法,可以有效地将NV12视频帧转化为JPEG图片,适用于音视频处理场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  在网上找了好几套,结果都不对。后来终于找到一套,还缺了一点。于是连蒙带猜,终于保存成功了。

  • github的开源

吾已将此代码开源到github,会进行维护工作。请优待去github:

GitHub - quantum6/NV12ToJpgByJpegLib

  • 编译jpeglib

LINUX下载编译jpeglib_柳鲲鹏的博客-优快云博客_jpeglib库linux下载

  • 源码
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

#include<jpeglib.h>

#define JPEG_QUALITY 75

int Nv12ToJpgFile(const char *pJpgFile,
    const char* pYUVBuffer, const int nWidth, const int nHeight)
{
    struct jpeg_compress_struct cinfo;
    struct jpeg_error_mgr jerr;
    JSAMPROW row_pointer[1];  
    FILE * pJpegFile = NULL;
    unsigned char *yuvbuf = NULL;
    unsigned char *ybase = NULL, *ubase = NULL;
    int i=0, j=0;
    int idx=0;
 
    cinfo.err = jpeg_std_error(&jerr);
    jpeg_create_compress(&cinfo);
 
    if ((pJpegFile = fopen(pJpgFile, "wb")) == NULL)
    {    
        return -1;
    }    
    jpeg_stdio_dest(&cinfo, pJpegFile);

    // image width and height, in pixels

    cinfo.image_width      = nWidth;
    cinfo.image_height     = nHeight;    
    cinfo.input_components = 3;    // # of color components per pixel
    cinfo.in_color_space   = JCS_YCbCr;  //colorspace of input image
    jpeg_set_defaults(&cinfo);
    jpeg_set_quality(&cinfo, JPEG_QUALITY, TRUE );

    cinfo.jpeg_color_space = JCS_YCbCr;
    cinfo.comp_info[0].h_samp_factor = 2;
    cinfo.comp_info[0].v_samp_factor = 2;
    jpeg_start_compress(&cinfo, TRUE);

    yuvbuf=(unsigned char *)malloc(nWidth*3);
    if(yuvbuf == NULL)
    {
        return -1;
    }
    memset(yuvbuf, 0, nWidth*3);

    ybase=(unsigned char *)pYUVBuffer;
    ubase=(unsigned char *)(pYUVBuffer+nWidth*nHeight);
    while (cinfo.next_scanline < cinfo.image_height)
    {
        idx=0;
        for(i=0;i<nWidth;i++)
        {   
            yuvbuf[idx++]=ybase[i + j * nWidth];
            yuvbuf[idx++]=ubase[j/2 * nWidth+(i/2)*2];
            yuvbuf[idx++]=ubase[j/2 * nWidth+(i/2)*2+1];
        }  
        row_pointer[0] = yuvbuf;
        jpeg_write_scanlines(&cinfo, row_pointer, 1);
        j++;
    }

    jpeg_finish_compress( &cinfo);
    jpeg_destroy_compress(&cinfo);
    fclose(pJpegFile);

    return 0;
}

int main(int argc, char** argv)
{
}
  • 编译

我试图使用pkgconfig,失败。

gcc \
    Nv12ToJpg.c \
    -I /usr/local/include \
    -L /usr/lib/ -ljpeg

#    `pkg-config --cflags --libs libjpeg`

评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

柳鲲鹏

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

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

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

打赏作者

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

抵扣说明:

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

余额充值