从MySQL获取Blob图片转JSON后,在Android中转为Bitmap求助
Alright, let's get this sorted out for you. The main issue here is that raw Blob data can't be directly sent via JSON (since JSON only handles text-based data), so we need to adjust your PHP code first, then handle the conversion on the Android side.
Step 1: Fix Your PHP Code to Send Image Data Correctly
When you pull the image Blob from your database, you need to convert it to a Base64-encoded string before adding it to your JSON response. This ensures the binary data is safely transmitted as text. Here's the updated PHP code:
$sql = "SELECT * FROM bim WHERE category = '$category'"; $r = mysqli_query($conn,$sql); $result = array(); while($res = mysqli_fetch_array($r)){ array_push($result,array( "signText"=>$res['signText'], "image"=>base64_encode($res['image']) // Convert Blob to Base64 string for JSON compatibility )); } echo json_encode(array("result"=>$result)); mysqli_close($conn);
Quick security note: Your current SQL query is vulnerable to SQL injection. For better security, use prepared statements instead:
$stmt = $conn->prepare("SELECT * FROM bim WHERE category = ?"); $stmt->bind_param("s", $category); $stmt->execute(); $result = $stmt->get_result(); $responseArray = array(); while($res = $result->fetch_assoc()){ array_push($responseArray,array( "signText"=>$res['signText'], "image"=>base64_encode($res['image']) )); } echo json_encode(array("result"=>$responseArray)); $stmt->close(); mysqli_close($conn);
Step 2: Convert Base64 String to Bitmap in Android
Once your PHP API is sending the Base64-encoded image, you can parse the JSON response and convert the string to a Bitmap in your Android app. Here's how to do it:
1. Parse the JSON Response
First, extract the Base64 image string from the JSON result array. This example uses native Android JSON parsing:
// Assume you've already fetched the JSON response into a String called jsonResponse try { JSONObject rootObject = new JSONObject(jsonResponse); JSONArray resultArray = rootObject.getJSONArray("result"); for (int i = 0; i < resultArray.length(); i++) { JSONObject item = resultArray.getJSONObject(i); String signText = item.getString("signText"); String imageBase64 = item.getString("image"); // Convert the Base64 string to a Bitmap Bitmap imageBitmap = convertBase64ToBitmap(imageBase64); // Use the bitmap (e.g., set it to an ImageView) // yourImageView.setImageBitmap(imageBitmap); } } catch (JSONException e) { e.printStackTrace(); }
2. Implement the Conversion Function
Create a helper method to handle the Base64-to-Bitmap conversion. This also accounts for any optional data URI prefixes (like data:image/png;base64,) that might be present:
private Bitmap convertBase64ToBitmap(String base64String) { try { // Remove data URI prefix if present if (base64String.contains(",")) { base64String = base64String.split(",")[1]; } // Decode Base64 string to byte array byte[] imageBytes = Base64.decode(base64String, Base64.DEFAULT); // Convert byte array to Bitmap return BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length); } catch (Exception e) { e.printStackTrace(); return null; } }
3. Handle Large Images (Avoid OOM Errors)
If your images are large, you might run into OutOfMemoryError. To fix this, use BitmapFactory.Options to downscale the image:
private Bitmap convertBase64ToBitmap(String base64String) { try { if (base64String.contains(",")) { base64String = base64String.split(",")[1]; } byte[] imageBytes = Base64.decode(base64String, Base64.DEFAULT); BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 2; // Reduce image dimensions by 50% (adjust as needed) options.inPreferredConfig = Bitmap.Config.RGB_565; // Uses less memory than ARGB_8888 return BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length, options); } catch (Exception e) { e.printStackTrace(); return null; } }
内容的提问来源于stack exchange,提问作者pienapeace

