How to get image resource size in bytes with PHP and GD?

后端 未结 5 670
旧时难觅i
旧时难觅i 2020-12-10 06:42

I\'m resizing images with php gd. The result is image resources that i want to upload to Amazon S3. It works great if i store the images on disk first but i would like to up

相关标签:
5条回答
  • 2020-12-10 07:16

    This also works:

    $img = imagecreatetruecolor(100,100);
    
    // ... processing
    
    ob_start();              // start the buffer
    imagejpeg($img);         // output image to buffer
    $size = ob_get_length(); // get size of buffer (in bytes)
    ob_end_clean();          // trash the buffer
    

    And now $size will have your size in bytes.

    0 讨论(0)
  • 2020-12-10 07:17

    You might look at the following answer for help. It works for generic memory changes in php. Although since overhead could be involved it might be more of an estimation.

    Getting size of PHP objects

    0 讨论(0)
  • 2020-12-10 07:20

    Save the image file in the desired format to a tmp dir, and then use filesize() http://php.net/manual/de/function.filesize.php before uploading it to S3 from disk.

    0 讨论(0)
  • 2020-12-10 07:25

    I can't write on php://memory with imagepng, so I use ob_start(), ob_get_content() end ob_end_clean()

    $image = imagecreatefrompng('./image.png'); //load image
    // do your processing here
    //...
    //...
    //...
    ob_start(); //Turn on output buffering
    imagejpeg($image); //Generate your image
    
    $output = ob_get_contents(); // get the image as a string in a variable
    
    ob_end_clean(); //Turn off output buffering and clean it
    echo strlen($output); //size in bytes
    
    0 讨论(0)
  • 2020-12-10 07:27

    You could use PHP's memory i/o stream to save the image to and subsequently get the size in bytes.

    What you do is:

    $img = imagecreatetruecolor(100,100);
    // do your processing here
    // now save file to memory
    imagejpeg($img, 'php://memory/temp.jpeg'); 
    $size = filesize('php://memory/temp.jpeg');
    

    Now you should know the size

    I don't know of any (gd)method to get the size of an image resource.

    0 讨论(0)
提交回复
热议问题