我无法从图库加载图片并将其设置为ImageView

时间:2016-04-29 09:13:10

标签: android imageview

我尝试将图片设置为来自图库的ImageView。

public class CollageCreateActivity extends AppCompatActivity {
    private static final String TAG ="MyLogs" ;
    Draw2d draw2d;
    static final int GALLERY_REQUEST = 1;
    private final int TAKE_PICTURE_CAMERA = 2;
    private Uri mOutputFileUri;
    ArrayList<CollageView> collageViewList1;
    ArrayList<CollageView> collageViewList2;
    float width;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.collage_creator);
        collageViewList1 = new ArrayList<>();
        collageViewList2 = new ArrayList<>();
        Data data = new Data();
        draw2d = new Draw2d(this);
        LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
        FrameLayout frameLayout = (FrameLayout) findViewById(R.id.frame_1);
        if (frameLayout != null) {
            frameLayout.addView(draw2d);
        }
        createCollage(data, layout);
        if (layout != null) {
            layout.bringToFront();
        }
        click();

    }


    public void createCollage(Data data, LinearLayout layout) {
        ArrayList<Integer> list = new ArrayList<>();
        list.add((int) data.getMap().get("mainLayout"));
        list.add((int) data.getMap().get("firstLayout"));
        list.add((int) data.getMap().get("secondLayout"));
        final LinearLayout layout1 = new LinearLayout(this);
        final LinearLayout layout2 = new LinearLayout(this);
        LinearLayout[] massLay = {layout, layout1, layout2};
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        params.weight = 1;
        layout1.setLayoutParams(params);
        layout2.setLayoutParams(params);
        for (int i = 0; i < (int) data.getMap().get("layButt1"); i++) {
            final Button button = new Button(this);
            button.setLayoutParams(params);
            button.setTextSize(50);
            button.setId(i);
            button.setPadding(16, 16, 16, 16);
            button.setText(R.string.plus);
            layout1.addView(button);

            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    layout1.removeView(v);
                    CollageView collageView = new CollageView(CollageCreateActivity.this);
                    saveFromGallery();
                    layout1.addView(collageView);
                    collageView.setOnTouchListener(new MultiTouchListener());
                    collageViewList1.add(collageView);
                }
            });
        }
        for (int j = 0; j < (int) data.getMap().get("layButt2"); j++) {
            Button button2 = new Button(this);
            button2.setLayoutParams(params);
            button2.setTextSize(50);
            button2.setId(j);
            button2.setPadding(16, 16, 16, 16);
            button2.setText(R.string.plus);
            layout2.addView(button2);

            button2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    layout2.removeView(v);
                    CollageView collageView = new CollageView(CollageCreateActivity.this);
                    layout2.addView(collageView);
                    collageView.setOnTouchListener(new MultiTouchListener());
                    width = layout2.getWidth();
                    collageViewList2.add(collageView);

                }
            });
        }
        for (int x = 0; x < list.size(); x++) {
            if (list.get(x) == 0) {
                massLay[x].setOrientation(LinearLayout.HORIZONTAL);
            } else {
                massLay[x].setOrientation(LinearLayout.VERTICAL);
            }
        }
        layout.addView(layout1);
        layout.addView(layout2);
    }

    public void click() {
        Button button = (Button) findViewById(R.id.butt);

        if (button != null) {
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    for (int i = 0; i < collageViewList1.size(); i++) {
                        collageViewList1.get(i).setDrawingCacheEnabled(true);
                        Bitmap bitmap1 = Bitmap.createBitmap(collageViewList1.get(i).getDrawingCache());
                        collageViewList1.get(i).setDrawingCacheEnabled(false);
                        draw2d.listBitmap.add(bitmap1);

                        draw2d.listX.add(collageViewList1.get(i).getX());
                        draw2d.listY.add(collageViewList1.get(i).getY());
                        Log.d("TAG", collageViewList1.get(i).getX() + "  " + collageViewList1.get(i).getY());
                    }
                    for (int i = 0; i < collageViewList2.size(); i++) {
                        collageViewList2.get(i).setDrawingCacheEnabled(true);
                        Bitmap bitmap2 = Bitmap.createBitmap(collageViewList2.get(i).getDrawingCache());
                        collageViewList2.get(i).setDrawingCacheEnabled(false);
                        draw2d.listBitmap.add(bitmap2);

                        draw2d.listX.add(collageViewList2.get(i).getX() + width);
                        draw2d.listY.add(collageViewList2.get(i).getY());
                        Log.d("TAG", collageViewList1.get(i).getX() + "  " + collageViewList1.get(i).getY());
                    }
                    draw2d.setDrawingCacheEnabled(true);
                    Bitmap bitmap = Bitmap.createBitmap(draw2d.getDrawingCache());
                    draw2d.setDrawingCacheEnabled(false);
                    draw2d.invalidate();
                }
            });
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Bitmap bitmap = null;
        InputStream imageStream = null;
        CollageView collageView = new CollageView(CollageCreateActivity.this);
        switch(requestCode) {
            case GALLERY_REQUEST:
                if(resultCode == RESULT_OK){
                    Uri selectedImage = data.getData();
                    try {
                      imageStream=getContentResolver().openInputStream(selectedImage);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                    bitmap= BitmapFactory.decodeStream(imageStream);
                    Log.d(TAG, "сетим з галереї1");
                    collageView.setImageBitmap(bitmap);

                    Log.d(TAG, "сетим з галереї");


                }
                break;
            case TAKE_PICTURE_CAMERA:
                if (data != null) {
                    if (data.hasExtra("data")) {
                        Bitmap thumbnailBitmap = data.getParcelableExtra("data");
                        collageView.setImageBitmap(thumbnailBitmap);

                    }
                } else {
                        collageView.setImageURI(mOutputFileUri);

                }

        }
    }
    private void saveFromGallery(){
        Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
        photoPickerIntent.setType("image/*");
        startActivityForResult(photoPickerIntent, GALLERY_REQUEST);
    }
}

当我尝试从文件夹设置图像&#34; drawrable&#34;它的工作,但如果我尝试加载图像并从画廊设置它不起作用,我所有的&#34; W / EGL_genymotion:eglSurfaceAttrib未实现&#34;在日志中

1 个答案:

答案 0 :(得分:2)

在这种情况下,您必须创建一个内容提供程序,用于将本地(应用程序的内部)文件共享到相机活动中。当您尝试从相机拍照时

试试这段代码:   内容提供商类

public class MyFileContentProvider extends ContentProvider {

public static final Uri CONTENT_URI =     

Uri.parse("content://com.example.camerademo/");

private static final HashMap<String, String> MIME_TYPES = new      

HashMap<String, String>();

static {

 MIME_TYPES.put(".jpg", "image/jpeg");

 MIME_TYPES.put(".jpeg", "image/jpeg");

}

@Override

public boolean onCreate() {

try {

 File mFile = new File(getContext().getFilesDir(), "newImage.jpg");

 if(!mFile.exists()) {

  mFile.createNewFile();

  }

  getContext().getContentResolver().notifyChange(CONTENT_URI, null);

  return (true);

  } catch (Exception e) {

  e.printStackTrace();

  return false;

  }

  }

  @Override

  public String getType(Uri uri) {

  String path = uri.toString();

  for (String extension : MIME_TYPES.keySet()) {

  if (path.endsWith(extension)) {

  return (MIME_TYPES.get(extension));

  }

  }

  return (null);

  }

  @Override

  public ParcelFileDescriptor openFile(Uri uri, String mode)

  throws FileNotFoundException {

  File f = new File(getContext().getFilesDir(), "newImage.jpg");

   if (f.exists()) {

  return (ParcelFileDescriptor.open(f,

   ParcelFileDescriptor.MODE_READ_WRITE));

   }

   throw new FileNotFoundException(uri.getPath());

   }

   @Override

   public Cursor query(Uri url, String[] projection, String selection,

   String[] selectionArgs, String sort) {

   throw new RuntimeException("Operation not supported");

   }

  @Override

  public Uri insert(Uri uri, ContentValues initialValues) {

  throw new RuntimeException("Operation not supported");

  }

  @Override

  public int update(Uri uri, ContentValues values, String where,

  String[] whereArgs) {

  throw new RuntimeException("Operation not supported");

 }

 @Override

 public int delete(Uri uri, String where, String[] whereArgs) {

 throw new RuntimeException("Operation not supported");

 }

 } 

Home.java:

public class Home extends Activity implements OnClickListener{

/** Called when the activity is first created. */

 private final int CAMERA_RESULT = 1;

 private final String Tag = getClass().getName();

 Button button1;

 ImageView imageView1;

 @Override

  public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);



    button1 = (Button)findViewById(R.id.button1);

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

    button1.setOnClickListener(this);

 }

 public void onClick(View v) {

 PackageManager pm = getPackageManager();

 if (pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {

 Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

 i.putExtra(MediaStore.EXTRA_OUTPUT, MyFileContentProvider.CONTENT_URI);

 startActivityForResult(i, CAMERA_RESULT);

 } else {

 Toast.makeText(getBaseContext(), "Camera is not available",      

 Toast.LENGTH_LONG).show();

 }   }



  @Override

  protected void onActivityResult(int requestCode, int resultCode, Intent   

  data) {

  super.onActivityResult(requestCode, resultCode, data);

  Log.i(Tag, "Receive the camera result");

  if (resultCode == RESULT_OK && requestCode == CAMERA_RESULT) {

  File out = new File(getFilesDir(), "newImage.jpg");

  if(!out.exists()) {

  Toast.makeText(getBaseContext(),

  "Error while capturing image", Toast.LENGTH_LONG)

  .show();

  return;

  }

  Bitmap mBitmap = BitmapFactory.decodeFile(out.getAbsolutePath());

  imageView1.setImageBitmap(mBitmap);

  }

  }



  @Override

  protected void onDestroy() {

  super.onDestroy();

  imageView1 = null;

  }

  } 
  hope it will help you,otherwise u will contact me my email   

  id:daminimehra28@gmail.com