【问题标题】:How to upload long blob (image) to mysql database using java and retrieve in php?如何使用java将长blob(图像)上传到mysql数据库并在php中检索?
【发布时间】:2016-08-14 11:40:38
【问题描述】:

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

我需要使用 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

【问题讨论】:

  • 答案是通过将文件存储在数据库中,您的生活变得不必要地复杂化了。将文件存储在文件系统上更简单、更有效(从编码和存储/检索的角度来看)。
  • 请让我想想该怎么做

标签: php android mysql blob


【解决方案1】:
 /**
*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;


}

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

现在是安卓部分。

在 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);

【讨论】:

  • 我已经尝试了上面的代码,它给了我profile_pic 变量的结果但是当我用图像标签尝试它时它仍然没有显示,我只是得到一个带有损坏图像的图标.
  • 您已经将图像保存为 base64 格式,对吧?我完全错过了。所以在php中你不再需要base64_encode()函数,所以我正在更新我的代码,如果我错了,请纠正我。
  • 很遗憾android开发部分的解码没有显示图片
  • logcat 一定有错误是什么..可以分享一下吗?
  • 我已经解决了。我在我的 SQLite DB 中只存储字符串而不是 blob
猜你喜欢
  • 2016-05-26
  • 1970-01-01
  • 1970-01-01
  • 2020-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-27
  • 2017-12-07
相关资源
最近更新 更多