如何使用java将长blob(图像)上传到mysql数据库并在php中检索?
我正在开发一个项目,我需要将图像上传到数据库并从数据库中检索相同的项目。如何使用java将长blob(图像)上传到mysql数据库并在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;
}
OK试试这个代码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);
我已经试过上面的代码,它给了'profile_pic'变量的结果,但是当我用图像标签尝试它时,它仍然没有显示任何东西,我只是得到一个破碎的图标图片。 – silverFoxA
你已经将图像保存为base64格式了吗?我完全错过了。所以在PHP中,你不需要'base64_encode()'函数,所以我正在更新我的代码,纠正我,如果我错了。 – Archish
不幸的是,在android开发部分解码没有显示图像 – silverFoxA
答案是你通过将文件存储在数据库中使你的生活不必要地复杂化。它更简单,更高效(从编码和存储/检索的角度来看)将文件存储在文件系统上。 – e4c5
请让我想想做什么 – silverFoxA