Creating an image without storing it as a local file

前端 未结 8 971
时光取名叫无心
时光取名叫无心 2020-12-01 08:45

Here\'s my situation - I want to create a resized jpeg image from a user uploaded image, and then send it to S3 for storage, but am looking to avoid writing the resized jpeg

相关标签:
8条回答
  • 2020-12-01 09:21

    Most people using PHP choose either ImageMagick or Gd2

    I've never used Imagemagick; the Gd2 method:

    <?php
    
    // assuming your uploaded file was 'userFileName'
    
    if ( ! is_uploaded_file(validateFilePath($_FILES[$userFileName]['tmp_name'])) ) {
        trigger_error('not an uploaded file', E_USER_ERROR);
    }
    $srcImage = imagecreatefromjpeg( $_FILES[$userFileName]['tmp_name'] );
    
    // Resize your image (copy from srcImage to dstImage)
    imagecopyresampled($dstImage, $srcImage, 0, 0, 0, 0, RESIZED_IMAGE_WIDTH, RESIZED_IMAGE_HEIGHT, imagesx($srcImage), imagesy($srcImage));
    
    // Storing your resized image in a variable
    ob_start(); // start a new output buffer
      imagejpeg( $dstImage, NULL, JPEG_QUALITY);
      $resizedJpegData = ob_get_contents();
    ob_end_clean(); // stop this output buffer
    
    // free up unused memmory (if images are expected to be large)
    unset($srcImage);
    unset($dstImage);
    
    // your resized jpeg data is now in $resizedJpegData
    // Use your Undesigned method calls to store the data.
    
    // (Many people want to send it as a Hex stream to the DB:)
    $dbHandle->storeResizedImage( $resizedJpegData );
    ?>
    

    Hope this helps.

    0 讨论(0)
  • 2020-12-01 09:25

    This can be done using the GD library and output buffering. I don't know how efficient this is compared with other methods, but it doesn't require explicit creation of files.

    //$image contains the GD image resource you want to store
    
    ob_start();
    imagejpeg($image);
    $jpeg_file_contents = ob_get_contents();
    ob_end_clean();
    
    //now send $jpeg_file_contents to S3
    
    0 讨论(0)
提交回复
热议问题