PHP:将base64转换为图像

时间:2015-12-02 01:03:06

标签: php

public function addNewCategory($category_title, $strImage) {

    // get the image from the base64 string.
    $strImage = str_replace('data:image/png;base64,', '', $strImage);
    $strImage = str_replace(' ', '+', $strImage);
    $strImage = base64_decode($strImage);

    // set the path name of where the image is to be stored.
    $path = dirname(__FILE__).'/category_images/'.$category_title.".png";

    // save the image in the path.
    file_put_contents($path, $image);

    // insert category and the image path into the MySQL database.
    $result = mysqli_query($this->db->connect(), "INSERT INTO category(category_title, path, created_at) VALUES ('$category_title', '$path', NOW())");

    if ($result) {
        return mysqli_fetch_array($result);
    } else {
        return false;
    }
}

运行此代码后,我发现具有类别标题名称的PNG文件存储在category_images目录中。但事实证明,PNG文件的大小为零,所以我认为将base64字符串转换为图像存在缺陷。

非常感谢您提供更正的提示。

被修改 此处的Base64字符串使用以下方法在Android中进行编码。

public String getStringFromImage(Bitmap bitmap) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
    byte[] imageBytes = stream.toByteArray();
    String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
    return encodedImage;
}

这是编码的字符串。我使用Log.i()方法得到了这个值。

iVBORw0KGgoAAAANSUhEUgAAAlgAAAJYCAIAAAAxBA+LAAAAA3NCSVQICAjb4U/gAAAgAElEQVR4nOzd2XNcV5Im+M/dz11iwb5xkyiltlSq1VVZOVVdM9M2bdaP/TJ/7zyMWc/YzFj3dM1YV1eVVVZWKZVaKXEnloi49xx374cbACmJFEUQoCjAf0aDASAQcQMg44uzuB/Cx/8eIYQQwmXFP/cFhBBCCD+nCMIQQgiXWgRhCCGESy2CMIQQwqUWQRhCCOFSiyAMIYRwqUUQhhBCuNQiCEMIIVxqEYQhhBAutQjCEEIIl1oEYQghhEstgjCEEMKlFkEYQgjhUosgDCGEcKlFEIYQQrjUIghDCCFcahGEIYQQLrUIwhBCCJdaBGEIIYRLLYIwhBDCpRZBGEII4VKLIAwhhHCp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poVO78/D+F7du/fGzP3359VcwoBmjaaGEbgHGmIz6rr/9Wb7zDe7fQj8Dg0HmAggoRoQhhHCWzr98wofmmQ5mTNdw5Sbv3uymm8h5WV2wrJcH4OTF+qMqJaoIYHJfnYxvXr/+xpVrb75xtVlu9YSrWV+OixTE3a3AXd2dlouI4CQAbFhIXJ6/6wZvjysThmXCwSkeVo9Cx6NJdvhQyU+wVKk7tCzDF8IMZk6OAkuOZpTWp7vXtrd3V9b+eTT5h6+/LH2RrhNOGeRZZwJIM77xPiZruU749k9YHBoniOBZncFDCCGc1vkHoRAzGQwpYW19vHetX90uWZLXUBjUoYAB5jCH1bW79+NmfOPG9XfeuHl

根据编码的字符串,data:image/png;base64,不包含在字符串的前面。我想现在这就是PNG文件没有正确制作的原因。在这里可以做些什么来解决这个问题?

1 个答案:

答案 0 :(得分:7)

编码数据是图像文件的内容,data:image/png;base64,仅在您将图像数据填入HTML时使用。

将数据放入HTML源会使源头膨胀,减慢初始页面加载速度,使浏览器无法并行下载大量资源(如图像),并使图像在页面之间无法缓存。除非你没有别的选择,否则不要这样做。

简单地将图像转换回文件:

file_put_contents('foo.png', base64_decode($str));

或者让PHP脚本伪装成图像:

header('Content-Type: image/png');
echo base64_decode($str);

或者做我刚刚告诉你不要这样做的事情,因为从来没有这样做有很多方法来这样做,我会超级失望和你一起,如果这是你从这个答案中拿走的东西:

printf('<img src="data:image/png;base64,%s" />', $str);