创建图像而不将其存储为本地文件 [英] Creating an image without storing it as a local file

查看:156
本文介绍了创建图像而不将其存储为本地文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的情况 - 我想从用户上传的图像创建一个调整大小的jpeg图像,然后将其发送到S3进行存储,但我希望避免将调整大小的jpeg写入磁盘,然后为S3请求重新加载它。

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 to the disk and then reloading it for the S3 request.

有没有办法在内存中完全执行此操作,图像数据JPEG格式化,保存在变量中?

Is there a way to do this completely in memory, with the image data JPEG formatted, saved in a variable?

推荐答案

大多数人使用PHP选择 ImageMagick Gd2

Most people using PHP choose either ImageMagick or Gd2

我从未使用过Imagemagick; 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 );
?>

希望这会有所帮助。

这篇关于创建图像而不将其存储为本地文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆