如何使用 java 将长 blob(图像)上传到 mysql 数据库并在 php 中检索?

How to upload long blob (image) to mysql database using java and retrieve in php?

我正在做一个项目,我需要将图像上传到数据库并从数据库中检索图像。

我需要使用 java 从 android 设备上传图像。 这是我实现的

Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
            // Log.d(TAG, String.valueOf(bitmap));
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want.
            byte[] byte_arr = stream.toByteArray();
            image_str = Base64.encodeToString(byte_arr, Base64.DEFAULT);

我正在将字节数组插入数据库。 这是我的 php 代码来检索相同的代码 :

 /**
*Get profile_pic*/
public function callmethod($userId){
    $stmt = $this->conn->prepare("SELECT profile_pic FROM users WHERE unique_id=?");
    $stmt->bind_param('s',$userId); 
    //$result = mysql_query($query) or die(mysql_error()); 
    //$photo = mysql_fetch_array($result); 
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($profile_pic);
    $stmt->fetch();
     //$obj->picture = base64_encode($profile_pic);
    //echo $obj;

    header("Content-Type: image/jpeg");
echo '<img src="data:image/jpeg;base64,<?php echo base64_encode($profile_pic); ?>" />';
}

我在这里面临的问题是文件正在上传到数据库,但是当我从数据库中检索图像时,变量 $profile_pic 为空,因此图像没有显示。

我需要它能够使用 android 中的 java 检索图像。我可以通过仅使用 json 格式对检索的值进行编码来做到这一点吗?

请告诉我我做错了什么。 TIA

 /**
*Get profile_pic*/
public function callmethod($userId){
$stmt = $this->conn->prepare("SELECT profile_pic FROM users WHERE unique_id=?");
$stmt->bind_param('s',$userId); 
//$result = mysql_query($query) or die(mysql_error()); 
//$photo = mysql_fetch_array($result); 
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($profile_pic);
while ($stmt->fetch()) {
    echo "<img src='data:image/jpeg;base64,".$profile_pic."' />";
}
 //$obj->picture = base64_encode($profile_pic);
//echo $obj;


}

可以试试这个代码 this.you 不需要 header("Content-Type: image/jpeg"); 功能。这是您的 php 代码中的错误。此代码将使用 basc64 创建 img 标签。

现在 android 部分。

在 php 中更改此设置。

while ($stmt->fetch()) {
    echo "<img src='data:image/jpeg;base64,".$profile_pic."' />";
}

while ($stmt->fetch()) {
    echo $profile_pic;
}

这将是您的 android 部分。

byte[] decodedString = Base64.decode(strBase64, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); 
image.setImageBitmap(decodedByte);