imagecreatefromstring():数据不是可识别的格式

时间:2017-02-14 14:16:54

标签: php

以下是我获取图片的方式:

$coverurl  = 'https://api.someurl/api/v1/img/' . $somenumber . '/l';
//$iheaders contains: 'Content-type' => 'image/jpeg'
$iresponse = wp_remote_get($coverurl, $iheaders);
$img = $iresponse['body'];
$testimg = base64_encode($img);

当我用img-tag回显$ testimg时,一切正常。

echo '<img class="attachment-shop_single size-shop_single wp-post-image" src="data:image/jpeg;base64,'.$testimg.'" width="274" />';

由于我需要将字符串转换为jpg并将其保存到我的uploads文件夹,因此我尝试使用imagecreatefromstring()

$imgx = imagecreatefromstring($testimg);
        if ($imgx !== false) {
            header('Content-Type: image/jpeg');
            imagejpeg($imgx);
            imagedestroy($imgx);
        } else {
            echo 'An error occurred.';
        }

但由于以下警告,我从未达到保存任何东西的程度:

 Warning: imagecreatefromstring(): Data is not in a recognized format in /etc.

当我回复$testimg时,我得到:

/9j/4AAQSkZJRgABAQAAAQABAAD ...Many number and characters.. Ggm2JUsEvfqnxAhGFDP/9k=

我必须做些什么才能让createimagefromstring工作?我是否必须修改$testimg字符串?谢谢你的兴趣。

2 个答案:

答案 0 :(得分:6)

方法imagecreatefromstring不接受base_64编码的字符串。试试这个:

$imgx = imagecreatefromstring($img); // Contents of $iresponse['body']

您可以在文档页面(上面链接)的最顶层评论中看到这一点:

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

$im = imagecreatefromstring($data);

答案 1 :(得分:0)

在查看了代码https://codex.wordpress.org/Function_Reference/wp_insert_attachment之后,我找到了解决方案:

//get the image from internet
$coverurl  = 'https://api.someurl/api/v1/img/' . $somenumber . '/l';
$iresponse = wp_remote_get($coverurl, $iheaders);
$img = $iresponse['body'];
$directory = "/".date('Y')."/".date('m')."/";
$wp_upload_dir = wp_upload_dir();
//encode $img as with html image tag
$imgdata = base64_encode($img);
$filename = "gtb_". $isbnraw.".jpg";
$fileurl = "../wp-content/uploads".$directory.$filename;
$filetype = wp_check_filetype( basename($fileurl), null);
file_put_contents($fileurl, $img);
$attachment = array(
    'guid' => $wp_upload_dir['url'] . '/' . basename( $fileurl ),
    'post_mime_type' => $filetype['type'],
    'post_title' => preg_replace('/\.[^.]+$/', '', basename($fileurl)),
    'post_content' => '',
    'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment($attachment, $fileurl, $post_id);
require_once('../wp-admin/includes/image.php');
// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata($attach_id, $fileurl);
wp_update_attachment_metadata($attach_id, $attach_data);
set_post_thumbnail($post_id, $attach_id);
//add media_category
wp_set_object_terms($attach_id, $mediacat, 'media_category');

这将base64转换为jpg并将其导入Wordpress并将其附加到帖子/产品。它似乎运作良好。谢谢你的兴趣。