首先,我将.png存储到mySQL数据库。我这样做是首先使.png成为位图,然后使用以下方法使其成为Base64:
private String prepPictureForDb(Bitmap bm){
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();
return Base64.encodeToString(byteArray, Base64.DEFAULT);
}
然后我在一个varchar(3000)列中将Base64字符串存储到我的数据库中(我认为这可能不是存储它的最好方法,但据我所知,它仍然可以工作)。
当我通过php从数据库中检索此String时,我使用以下代码:
<?php
//load and connect to MySQL database stuff
require("config.inc.php");
if (!empty($_POST)) {
//gets user's info based off of a username.
$query = "SELECT isAdmin, username, lastLogin, phone, email, image FROM Vamoose.user_accounts WHERE first_name = :first AND last_name = :last";
$query_params = array(':first' => $_POST['first'], ':last' => $_POST['last']);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
//die("Failed to run query: " . $ex->getMessage());
//or just use this use this one to product JSON data:
$response["success"] = 0;
$response["message"] = "Database Error. Please Try Again!";
die(json_encode($response));
}
//fetching all the rows from the query
$row = $stmt->fetch();
if ($row) {
$response["success"] = 1;
$response["isAdmin"] = $row["isAdmin"];
$response["username"] = $row["username"];
$response["lastLogin"] = $row["lastLogin"];
$response["phone"] = $row["phone"];
$response["email"] = $row["email"];
$response["image"] = base64_encode($row["image"]);
}else{
$response["success"] = 0;
}
echo json_encode($response);
}
?>
如您所见,我base64_encode($row["image"]);
然后echo json_encode($response);
回到Android Studio,我使用以下代码解码String:
String image = json.getString("image").toString();
byte[] decodedString = Base64.decode(this.image, Base64.DEFAULT);
Bitmap bm = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
问题是bm
为NULL
注意*:我已经针对这个主题的线程搜索了Stack Overflow,发现了很多匹配。但是,它们似乎都没有具体与我的问题有关。