2016-04-21 105 views
1

我正在開發一個項目,我需要將圖像上傳到數據庫並從數據庫中檢索相同的項目。如何使用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

+0

答案是你通過將文件存儲在數據庫中使你的生活不必要地複雜化。它更簡單,更高效(從編碼和存儲/檢索的角度來看)將文件存儲在文件系統上。 – e4c5

+0

請讓我想想做什麼 – silverFoxA

回答

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; 


} 

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); 
+0

我已經試過上面的代碼,它給了'profile_pic'變量的結果,但是當我用圖像標籤嘗試它時,它仍然沒有顯示任何東西,我只是得到一個破碎的圖標圖片。 – silverFoxA

+0

你已經將圖像保存爲base64格式了嗎?我完全錯過了。所以在PHP中,你不需要'base64_encode()'函數,所以我正在更新我的代碼,糾正我,如果我錯了。 – Archish

+0

不幸的是,在android開發部分解碼沒有顯示圖像 – silverFoxA