将base64编码的图像另存为BLOB到服务器端数据库

将base64编码的图像另存为BLOB到服务器端数据库

问题描述:

我正在使用以下代码从 Android应用中拍照:

I am taking a photograph from within my Android app using this code:

if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK){
        photo = (Bitmap) data.getExtras().get("data");
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        photo.compress(Bitmap.CompressFormat.JPEG, 40, baos);
        byte[] photoByte = baos.toByteArray();
        encodedImage = Base64.encodeToString(photoByte,Base64.DEFAULT);
    }

我正在通过POST将此字符串encodedImage发送到我的PHP服务器,并将其接收到$encodedImage.我有一个数据库,其中有一个类型为MEDIUMBLOB的字段myImage.我试图将encodedimage保存在myImage中,但是将其保存为损坏的图像.我尝试另存为base64_decode($encodedImage),但无论如何还是不起作用.

I am sending this String encodedImage to my PHP server through POST and receiving it to $encodedImage. I have a database where I have a field myImage of type MEDIUMBLOB. I tried to save the encodedimage in myImage but it is saved as corrupted image. I tried to save as base64_decode($encodedImage) but somehow that didn't work either.

我希望完成三件事:

  • 将图像保存到服务器端数据库(BLOB)

  • Save image to server-side database (BLOB)

在网页上显示图像

将其发送回Android应用.

Send it back to the Android app.

我面临着了解上述任务所需的不同格式的图像转换的问题.

对于我当前的项目,我不想将图像保存到文件夹并提供指向数据库的链接,因此该选项对我来说是关闭的.

For my current project, I don't want to save my image to folder and give link to the database, so that option is closed for me.

我的用于保存图像的PHP代码:

My PHP code to save the image:

$baseImage = $_POST['baseImage'];
$blobImage = base64_decode($baseImage);
$query = "INSERT INTO `complaints`(`myImage`,...) VALUES ('$blobImage',...)"
$result = mysqli_query($conn,$query);

在SQL前面加上关键字_binary"

Prefix your SQL with the keyword _binary"

$query = "INSERT INTO `complaints`
(`myImage`,...)
VALUES (_binary'".addcslashes($blobImage, "\x00\'\"\r\n")."',...)"

此外,使用CURL设置测试环境,以便您可以反复向其抛出base64编码的图像.这将是您需要大量调试的情况.

Also, setup a test environment with CURL so that you can throw base64 encoded images at it repeatedly. This is going to be a case where you need lots of debugging.

<?php
$f = fopen('sample.jpg.base64.txt', 'w');
$i = fopen('sample.jpg', 'r');
if (!$i) { die("cannot open sample.jpg\n"); } 
$bytes = '';
while ( ! feof($i)) { 
    $bytes .= fread($i, 4096);
}
fclose($i);
fputs($f, base64_encode( $bytes ) );
fclose($f);

然后使用curl重复发布它并调试PHP

And then use curl to post it repeatedly and debug your PHP

curl -X PUT "http://localhost/myimport.php" -F "baseImage=@./sample.jpg.base64.txt"

调整您的PHP脚本,只需将数据写到硬盘驱动器上的文件中,然后在其中进行检查即可.写出编码和解码的多个版本.

Adjust your PHP script to simply write out the data to a file on your hard drive and inspect it there. Write out multiple versions, both encoded and decoded.

就我个人而言,我不会使用base64从Android到PHP的字节,但是我会 使用base64在mysql中对它们进行编码.

Personally, I wouldn't base64 the bytes going from Android to PHP, but I would base64 encode them in mysql.