2017-08-17 41 views
0

我在mysql workbunch中創建了一個數據庫,並將類似blob的圖片存儲在它中。
現在我想在我的應用程序使用該圖片,如何從mysql glob類型獲取圖像

Class.forName("com.mysql.jdbc.Driver"); 
       try(Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sys", "root", "Elior204")){ 
        Statement stmt = con.createStatement(); 
        ResultSet rs = stmt.executeQuery("SELECT img FROM Sentences where id=1"); 
         ImageView image = (ImageView) findViewById(R.id.imageView1); 
        Blob b =rs.getBlob(1); 
        int blobLength = (int) b.length(); 
        byte[] blobAsBytes = b.getBytes(1, blobLength); 
        Bitmap btm =BitmapFactory.decodeByteArray(blobAsBytes,0,blobAsBytes.length); 
        image.setImageBitmap(btm); 
        con.close(); 

的問題是,如何我繼續嗎?

+0

你不能在Android中直接訪問mysql,你需要一個web服務來訪問mysql數據。 –

+0

當然,如果你[包括正確的權限](https://stackoverflow.com/a/18843518/783412) – hd1

+0

נשמהשלאבאדבראיתיכפרה –

回答

0
java.sql.Blob blob = rs.getBlob(1); 
byte[] imageContents = blob.getBytes(1, new Integer(blob.length()).intValue()); 

現在你可以按照你的意願操縱它。

根據您的評論,你想在你的應用程序中顯示它,要做到這一點,一個ImageView的添加到您的佈局和使用下面的代碼:

image = (ImageView) findViewById(R.id.imageView1); 

button = (Button) findViewById(R.id.btnChangeImage); 
button.setOnClickListener(new OnClickListener() { 

    @Override 
    public void onClick(View arg0) { 
      java.io.File tmpFileForImage = java.io.File.createTemporaryFile("image", ".png"); // or whatever your extension happens to be 
      java.io.BufferedOutputStream bos = new java.io.BufferedOutputStream(new java.io.FileOutputStream(tmpFileForImage); 
      bos.write(imageContents); 
      bos.close(); 
      image.setImageResource(tmpFileForImage.getAbsolutePath()); 
    }); 

未經檢驗的,但應該讓你在正確的軌道上。如果您需要進一步幫助,請留下另一條評論。

+1

我想在我的應用程序上顯示圖片,我該怎麼做? –

+0

請參閱我的編輯,@EliorSastiel – hd1

+1

我編輯我的問題,它仍然無法工作,你知道爲什麼嗎? –