2017-02-12 8 views
0

ギャラリーの画像の位置からビットマップにリソースをロードしようとしています。 "drawableId"に正しいテキストが設定されていますが、文字列と参照に設定されていますビットマップコード行では、このコード行 "Bitmap b = BitmapFactory.decodeResource(getResources(), a)"に "a"というエラーが表示されます。bitmapFactoryの文字列からリソース変数を取得する方法

aR.drawable.pg1に置き換えても問題ありません。

String a = drawableId.getText().toString();   
Bitmap b = BitmapFactory.decodeResource(getResources(), a); 
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); 
    fab.setOnClickListener(new View.OnClickListener() { 

     public void onClick(View view) { 
      postPicture(); 
     } 

     public boolean postPicture() { 
      String a = drawableId.getText().toString(); 

      Bitmap b = BitmapFactory.decodeResource(getResources(), (a)); 
      Intent share = new Intent(Intent.ACTION_SEND); 
      share.setType("image/*"); 
      ByteArrayOutputStream bytes = new ByteArrayOutputStream(); 
      b.compress(Bitmap.CompressFormat.JPEG, 100, bytes); 
      File f = new File(Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg"); 
      try { 
       f.createNewFile(); 
       FileOutputStream fo = new FileOutputStream(f); 
       fo.write(bytes.toByteArray()); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
      share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/temporary_file.jpg")); 
      startActivity(Intent.createChooser(share, "Share image File")); 

この問題を解決する方法はありますか?前もって感謝します!

+0

あなたはドキュメントをチェックする必要があります。必要な2番目のパラメータは、文字列ではなく必要なリソースIDであるintです。この** R.drawable.pg1 **は正常に動作するはずです – Raghunandan

+0

[decodeResource](https://developer.android.com/reference/android/graphics/BitmapFactory.html#decodeResource(android.content.res.Resources、% 20int))は、文字列ではなく2番目のパラメータとしてintをとります。あなたは本当にあなたのエラーメッセージを読むべきです –

+0

https://stackoverflow.com/a/38447612/115145 – CommonsWare

答えて

0

別の方法では、これを試してみてください。

int id = getResources().getIdentifier(a, "id", getPackageName()); 
Drawable drawable = getResources().getDrawable(id); 

Bitmap b = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Config.ARGB_8888); 
Canvas canvas = new Canvas(b); 
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); 
drawable.draw(canvas); 
関連する問題