基本上所有的对文件操作的API, 都迁移到的了PHP stream上, 所以, 绝大部分对文件操作的API都是支持Data URL的.
当某个API需要操作对象是文件的时候, 我们其实是可以采用Data URL让他接受一个文件内容字符串的.
比如在#62961中, 请求PHP提供一个exif_imagetypefromstring API, 因为目前的exif_imagetype API只接受文件名, 而提出者已经得到了文件内容在内存中, 不希望只能通过写到一个临时文件, 然后再调用exif_imagetype .
- <?php
- //we already have $bindata
- $tmpfile = tempnam('/tmp', 'upload');
- file_put_contents($tmpfile, $bin_data);
- $extension = image_type_to_extension(exif_imagetype($tmpfile));
- unlink($tmpfile);
那么, 这个时候, 我们就可以借助Data URL了:
- <?php
- //we already have $bindata
- $base64_data = base64_encode($bin_data);
- $extension =
- image_type_to_extension(exif_imagetype("data://image/;base64," . $base64_data ));
源码就是:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB8AAAAVCAYAAAC+NTVfAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAALEAAACxABrSO9dQAAAB90RVh0U29mdHdhcmUATWFjcm9tZWRpYSBGaXJld29ya3MgOLVo0ngAAAYaSURBVEhLlVUJTJRHFEYEhXIoQm0EQyKklkMOOSxqI1awUDUchogGEDEgoMJ6IaigIMgtDZcYVhCxQBEs5VixiNoCCgQTuZSG1sa2EUlLi0K9XV6/N4mEFbS6yWZ/+Gfmfdd7o6T0jh8iUu7r69O6evWq2lRb+H13d3dpV1fXo+rqanMzM7MZ73j01MvOnTs3/ciRIyoHDhwwCQ0NdUThkvb29vALFy7MfH3HyMjIhzKZLPDkyZN9MTEx/zg4OPjwXoCa9t4g2tra5ufk5Lj6+Ph4bdmy5S9vb286fvw4oUBPXV2d9ZsOLCwstMjLy3vq5ub2y549ezwA3Oy9it+5c2dWU1NTUnh4+PDKlSvJ1NSUDh48SElJSc/BrKG2ttbq1YHMrLOz87OioqJN165d29TT0+NXX18/vHHjRvL19X0O0DLss3pnBW7cuOGRkZHxk5WVFenq6hL8IwsLixcbNmyoOHPmjPN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