2017-02-12 2 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))는 문자열이 아닌 두 번째 매개 변수로 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);