2014-05-21 59 views
0

我想將位圖轉換爲uri轉換我正在使用谷歌圖片搜索api從這個api我從這個url得到的圖像URL我將它轉換爲位圖然後想從這個位圖轉換爲使用這個示例我得到空值的uri位圖到uri轉換android?

private class GetXMLTask extends AsyncTask<String, Void, Bitmap> { 
    @Override 
    protected Bitmap doInBackground(String... urls) { 
     Bitmap map = null; 
     for (String url : urls) { 
      map = downloadImage(url); 
     } 
     return map; 
    } 

    // Sets the Bitmap returned by doInBackground 
    @Override 
    protected void onPostExecute(Bitmap result) { 

     imagQest.setImageBitmap(result); 

     ByteArrayOutputStream bytes = new ByteArrayOutputStream(); 
     result.compress(Bitmap.CompressFormat.JPEG, 100, bytes); 
     String path = Images.Media.insertImage(ctx.getContentResolver(), 
       result, "Title", null); 
     LivLog.info(this.getClass(), "bit map conversion is" + result 
       + path); 

    } 

    // Creates Bitmap from InputStream and returns it 
    private Bitmap downloadImage(String url) { 
     Bitmap bitmap = null; 
     InputStream stream = null; 
     BitmapFactory.Options bmOptions = new BitmapFactory.Options(); 
     bmOptions.inSampleSize = 1; 

     try { 
      stream = getHttpConnection(url); 
      bitmap = BitmapFactory.decodeStream(stream, null, bmOptions); 
      // stream.close(); 
     } catch (IOException e1) { 
      e1.printStackTrace(); 
     } 
     return bitmap; 
    } 

    // Makes HttpURLConnection and returns InputStream 
    private InputStream getHttpConnection(String urlString) 
      throws IOException { 
     InputStream stream = null; 
     URL url = new URL(urlString); 
     URLConnection connection = url.openConnection(); 

     try { 
      HttpURLConnection httpConnection = (HttpURLConnection) connection; 
      httpConnection.setRequestMethod("GET"); 
      httpConnection.connect(); 

      if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) { 
       stream = httpConnection.getInputStream(); 
      } 
     } catch (Exception ex) { 
      ex.printStackTrace(); 
     } 
     return stream; 
    } 
} 
+0

什麼問題是什麼? –

+0

@BirajZalavadia我的問題是我上傳圖像到使用亞馬遜api的亞馬遜服務器,而我使用谷歌圖像搜索api從網絡搜索圖像使用此api後,我從這張圖片獲得了一個iamge url我下載圖像然後我得到了一個位圖形成這個位圖我想將uri轉換爲amazon iamge上傳,而我將位圖轉換爲uri上面的示例代碼我得到了空值。 –

回答

3

試試下面的代碼: -

public Uri getImageUri(Context inContext, Bitmap inImage) { 
    ByteArrayOutputStream bytes = new ByteArrayOutputStream(); 
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes); 
    String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null); 
    return Uri.parse(path); 
} 

更多信息請參見下面的鏈接: -

http://colinyeoh.wordpress.com/2012/05/18/android-getting-image-uri-from-bitmap/

+0

@Golup使用上面的代碼,這一行我得到錯誤fileString path = Images.Media.insertImage(ctx.getContentResolver(),\t \t \t \t result,「Title」,null);找不到 –

+0

你能顯示你的整個代碼嗎? – duggu

+0

上面的代碼,日誌消息我得到的路徑爲空 –