php - 创建图像而不将其存储为本地文件

标签 php image jpeg gd

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

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

最佳答案

大多数使用 PHP 的人都会选择 ImageMagickGd2

我从未使用过 Imagemagick; Gd2方法:

<?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 );
?>

希望这有帮助。

关于php - 创建图像而不将其存储为本地文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/189368/

相关文章:

php - 登录后如何在 Bootstrap 导航栏中显示登录用户名

html - 为什么 Chrome 的 img 元素的 onerror 事件只触发一次?

javascript - 鼠标悬停在 html 上更改图像

c++ - 如何在 Windows 8 上使用 C++ 将 .jpg 转换为 .png?

image-processing - Google PageSpeed 和 ImageMagick JPG 压缩

php - 如何安装/启用 PHP phar 扩展?

php - Laravel 5.4 关系不起作用无法附加第二个参数

php - CakePHP:使数据字段管理员只能编辑

android - 如何获取设备支持的最大图片尺寸?

jpeg - 解码部分JPEG文件