17
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHPでbase64から画像ファイル化

Posted at

概要

大学の授業でグループワークがあって, base64で送られてきた画像を保存することがあったので, その方法.

やり方

  1. base64_decode()でデコード
  2. 拡張子は, MIMEタイプから判断させるか, /区切りの文字列から得る
  3. あとは適当に保存

サンプル

<?php
$data = file_get_contents('profile.jpg');
$data = base64_encode($data); // これが送られてきたと仮定

$data = base64_decode($data);

// PHP 5.3.0 ~
$mime_type = finfo_buffer(finfo_open(), $data, FILEINFO_MIME_TYPE);
var_dump($mime_type); // string(10) "image/jpeg"

// PHP 7.2.0 ~
$type = finfo_buffer(finfo_open(), $data, FILEINFO_EXTENSION);
var_dump($type); // string(17) "jpeg/jpg/jpe/jfif"

まとめ

  • base64_decode()してfinfo_buffer()を使う
  • オプションはFILEINFO_MIME_TYPEでMIMEタイプからゴニョゴニョして拡張子を判定
  • PHP 7.2.0以上ならFILEINFO_EXTENSIONで拡張子が得られる
17
20
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?