Search code examples
ffmpeg

How to resize a picture using ffmpeg's sws_scale()?


I wanna resize a picture by using the ffmpeg's func--->sws_scale().

Is there any one knows how to do it?

Do you have the source code for this function?


Solution

  • First you need to create a SwsContext (you need to do this only once) :

    struct SwsContext *resize;
    resize = sws_getContext(width1, height1, AV_PIX_FMT_YUV420P, width2, height2, PIX_FMT_RGB24, SWS_BICUBIC, NULL, NULL, NULL);
    

    You need two frames for conversion, frame1 is the original frame, you need to explicitly allocate frame2 :

    AVFrame* frame1 = avcodec_alloc_frame(); // this is your original frame
    
    AVFrame* frame2 = avcodec_alloc_frame();
    int num_bytes = avpicture_get_size(AV_PIX_FMT_RGB24, width2, height2);
    uint8_t* frame2_buffer = (uint8_t *)av_malloc(num_bytes*sizeof(uint8_t));
    avpicture_fill((AVPicture*)frame2, frame2_buffer, AV_PIX_FMT_RGB24, width2, height2);
    

    You may use this part inside a loop if you need to resize each frame you receive :

    // frame1 should be filled by now (eg using avcodec_decode_video)
    sws_scale(resize, frame1->data, frame1->linesize, 0, height1, frame2->data, frame2->linesize);
    

    Note that I also changed pixel format, but you can use the same pixel format for both frames