繁体   English   中英

如何保存从 imagecreatefromstring() function 创建的图像?

[英]How to save an image created from imagecreatefromstring() function?

这是我的代码:

$data = 'iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABl'
       . 'BMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDr'
       . 'EX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r'
       . '8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==';
$data = base64_decode($data);

$im = imagecreatefromstring($data);
if ($im !== false) {
    header('Content-Type: image/png');
    imagepng($im);
    imagedestroy($im);

}
else {
    echo 'An error occurred.';
}

我想将以这种方式生成的图像保存到一个目录中。 我该怎么做呢?

这是imagepng的正确语法:

imagepng($im, "/path/where/you/want/save/the/png.png");

根据PHP手册

bool imagepng(resource $ image [,string $ filename [,int $ quality [,int $ filters]]])

filename - 保存文件的路径。

如果未设置或为NULL,则直接输出原始图像流。

下面的代码将有所帮助:

$data = 'code in bytes'; // replace with an image string in bytes
$data = base64_decode($data); // decode an image
$im = imagecreatefromstring($data); // php function to create image from string
// condition check if valid conversion
if ($im !== false) 
{
    // saves an image to specific location
    $resp = imagepng($im, $_SERVER['DOCUMENT_ROOT'].'folder_location/'.date('ymdhis').'.png');
    // frees image from memory
    imagedestroy($im);
}
else 
{
    // show if any error in bytes data for image
    echo 'An error occurred.'; 
}

请建议一些其他更好的方法!

Q:如果图片是JPG或者GIF怎么办?

答:当您使用 imagecreatefrom... 方法时,图像将作为未压缩的 bitmap 加载到 memory。此时并没有真正的图像类型。 您可以使用图像将其保存为您希望的任何类型...function。
来源: https://stackoverflow.com/a/7176074/3705191

但是如果我们想确定字节串的文件类型呢?

使用imagecreatefromstring( $data_string )之前,您作为 function 的参数提供的实际$data_string用于确定图像类型:

$data = base64_decode($data);
// imagecreatefromstring( $data ); -- DON'T use this just yet

$f = finfo_open();

$mime_type = finfo_buffer($f, $data, FILEINFO_MIME_TYPE);
// $mime_type will hold the MIME type, e.g. image/png

信用: https://stackoverflow.com/a/6061602/3705191

您必须将获得的字符串与常见图像文件的 MIME 类型( image/jpegimage/pngimage/gif等)进行比较。

$im = imagecreatefromstirng( $data );

if( $mime_type == "image/png" )
  imagepng( $im, "/path/where/you/want/save/the/png.png" );
if( $mime_type == "image/jpeg" )
  imagejpeg( $im, "/path/where/you/want/save/the/jpg_image.jpg" );
// ...

查看此List of Common MIME Types以供参考。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM