Search code examples
imagewinapilibjpeg

libJPEG WinAPI Error


Procedure read JPEG file

void read_jpeg_file(char *szNamaFile)
{
    size_t i;
    unsigned char* raw_image;
    JSAMPROW row_pointer[1];
    unsigned long location = 0;

    struct jpeg_error_mgr jerr;
    struct jpeg_decompress_struct cinfo ;

    errno_t err;
    FILE *infile;
    err = fopen_s(&infile, szNamaFile, "rb" );

    if (infile == NULL )
    {
        printf("Error opening jpeg file %s\n!", szNamaFile );
        exit(EXIT_FAILURE);
    }
    cinfo.err = jpeg_std_error(&jerr);

    /* create decompressor */
    jpeg_create_decompress(&cinfo);

    /* this makes the library read from infile */
    jpeg_stdio_src(&cinfo, infile );

    /* read jpeg header */
    jpeg_read_header(&cinfo, TRUE);

    /* decompress */
    jpeg_start_decompress(&cinfo);

    /*allocate memory */
    raw_image = (unsigned char*)malloc( cinfo.output_width*cinfo.output_height*cinfo.num_components );

    /* now actually read the jpeg into the raw buffer */
    row_pointer[0] = (unsigned char *)malloc( cinfo.output_width*cinfo.num_components );
    /* read scanlines */
    while (cinfo.output_scanline < cinfo.output_height) {
        jpeg_read_scanlines( &cinfo, row_pointer, 1 );
        for(i = 0; i < cinfo.image_width*cinfo.num_components; i++) 
            raw_image[location++] = row_pointer[0][i];
    }  

    /* clean up */
    jpeg_finish_decompress(&cinfo);
    jpeg_destroy_decompress(&cinfo);
    fclose( infile );
    free( row_pointer[0] );
}

Procedure Open File Dialog

void OpenDialog(HWND hWnd) 
{
    OPENFILENAME    ofn     = {sizeof(ofn)};

    ofn.hwndOwner       = hWnd;
    ofn.lpstrFilter     = TEXT("File BMP (*.BMP)\0*.BMP\0File JPG (*.JPG)\0*.JPG\0");
    ofn.nFilterIndex    = 1;
    ofn.lpstrFile       = szNamaFile;
    ofn.lpstrFile[0]    = '\0';
    ofn.lpstrTitle      = TEXT("Test ...");
    ofn.nMaxFile        = sizeof(szNamaFile);
    ofn.Flags           = OFN_FILEMUSTEXIST;

  if(GetOpenFileName(&ofn))
  {
      read_jpeg_file(ofn.lpstrFile);
  }
}

WM_COMMAND

case WM_COMMAND:
        if(HIWORD(wParam) != BN_CLICKED)
            break;
        switch(LOWORD(wParam))
        {
            case IDB_LOAD:
                OpenDialog(hWnd);
                break;
        }
        break;

Image doesn't show,, how to fix it? maybe I should send a message to WM_PAINT?
Sorry if I ask many questions ,, because I am still a beginner
Thank you and sorry for my bad english


Solution

  • To fix the first warning use fopen_s like this:

    FILE *infile;
    errno_t err = fopen_s(infile, szNamaFile, "rb");
    if(0 == err)
    {
        // Proceed with reading if file is opened properly
        ...
    }
    

    To fix the second warning, replace int with size_t:

    size_t i;
    for( i = 0; i < cinfo.image_width * cinfo.num_components; i++)