安卓:用摄像头采集集成库功能 [英] Android : Integrating gallery functionality with camera capture

查看:316
本文介绍了安卓:用摄像头采集集成库功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的一个Android项目中,我在这里用户可以在一个按钮点击,它就会打开相机上传图片的功能。上传按钮被隐藏,直到有图像拍摄和preVIEW所示。

I am working on an Android project in which I have the functionality where user can click on the a button and it will open the camera to upload the image. The upload button is hidden until there is image taken and shown in preview.

我想要做的是使用相同的上传按钮,这是我现在默认并单击它设置为可见的,我想开一个画廊,用户可以再使用选择图像,它会显示在preVIEW。

What I would like to do is to use the same upload button, which I have set to visible by default now and on clicking it, I would like to open a gallery, which the user can then use to select an image, and it would be shown in preview.

我有一个布尔标志来管理这个,如果标志是假的,那么画廊开在哪里,否则在preVIEW图像上传

I have a boolean flag to manage this, where if the flag is false, then gallery is opened, else the image in the preview is uploaded.

我有这个,但我不知道如何打开一个画廊,然后将图像发送到preVIEW,上传。我是新来的Andr​​oid程序,让好心考虑到这一点。

I have this, but I don't know how to open a gallery and then send the image to preview, to upload. I am new to Android programming, so kindly take that into consideration.

我搜索了类似的功能,但问题是,我还没有发现,如果这些功能都集成。

I searched for similar functionality, but the problem is, I have not found, where such features are integrated.

Java的code:

Java code :

    RobotoTextView BtnSelectImage;
    private ImageView ImgPhoto;

    CheckBox profilePhotoCheckBox;
    final RestaurantImageServiceImpl restaurantService = new RestaurantImageServiceImpl();

    private static final int CAMERA_PHOTO = 111;
    private Uri imageToUploadUri;

   private static volatile Bitmap reducedSizeBitmap;

    ByteArrayOutputStream stream = new ByteArrayOutputStream();

    private static boolean galleryFlag = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_restaurant_images);

  ImgPhoto = (ImageView) findViewById(R.id.userPhotoImageView);
        BtnSelectImage = (RobotoTextView) findViewById(R.id.userPhotoButtonSelect);
        profilePhotoCheckBox = (CheckBox)findViewById(R.id.profilePhotoCheckBox);
        BtnSelectImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    galleryFlag = true;
                    captureCameraImage();

                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(), "Couldn't load photo", Toast.LENGTH_LONG).show();
                }
            }
        });

        uploadImageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!(v == null)) {

                    if(!galleryFlag){
                        // I think the gallery open code should come here. 
                    }

                    if (profilePhotoCheckBox.isChecked()) {
                        uploadImage(true);
                    }else {
                        uploadImage(false);
                    }
                    new AlertDialog.Builder(AddPhotosForRestaurant.this)
                    .setTitle("Add more photos")
                            .setMessage("Are you sure you want to add more photos?")
                            .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    finish();
                                    startActivity(getIntent());
                                }
                            })
                            .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    Intent intent = new Intent(getApplicationContext(), RestaurantMenu.class);
                                    startActivity(intent);
                                    finish();
                                }
                            })
                            .setIcon(android.R.drawable.ic_dialog_alert)
                            .show();

                }
            }
        });

    }

    private Bitmap getBitmap(String path) {

        Uri uri = Uri.fromFile(new File(path));
        InputStream in = null;
        try {
            final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
            in = getContentResolver().openInputStream(uri);

            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(in, null, o);
            in.close();


            int scale = 1;
            while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) >
                    IMAGE_MAX_SIZE) {
                scale++;
            }
            Log.d("", "scale = " + scale + ", orig-width: " + o.outWidth + ", orig-height: " + o.outHeight);

            Bitmap b = null;
            in = getContentResolver().openInputStream(uri);
            if (scale > 1) {
                scale--;
                // scale to max possible inSampleSize that still yields an image
                // larger than target
                o = new BitmapFactory.Options();
                o.inSampleSize = scale;
                b = BitmapFactory.decodeStream(in, null, o);

                // resize to desired dimensions
                int height = b.getHeight();
                int width = b.getWidth();
                Log.d("", "1th scale operation dimenions - width: " + width + ", height: " + height);

                double y = Math.sqrt(IMAGE_MAX_SIZE
                        / (((double) width) / height));
                double x = (y / height) * width;

                Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x,
                        (int) y, true);
                b.recycle();
                b = scaledBitmap;
                System.gc();
            } else {
                b = BitmapFactory.decodeStream(in);
            }
            in.close();

            Log.d("", "bitmap size - width: " + b.getWidth() + ", height: " +
                    b.getHeight());
            return b;
        } catch (IOException e) {
            Log.e("", e.getMessage(), e);
            return null;
        }
    }

    private void captureCameraImage() {
        Intent chooserIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File f = new File(Environment.getExternalStorageDirectory(), "POST_IMAGE.jpg");
        chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
        imageToUploadUri = Uri.fromFile(f);
        startActivityForResult(chooserIntent, CAMERA_PHOTO);
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent(this, Login.class);
        StaticRestTemplate.setReplyString("");
        StaticRestTemplate.setLoggedInUser("");
        StaticRestTemplate.setJsessionid("");
        startActivity(intent);
        finish();
    }

    @Override
    protected void onActivityResult(final int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == CAMERA_PHOTO && resultCode == Activity.RESULT_OK) {
            if(imageToUploadUri != null){
                Uri selectedImage = imageToUploadUri;
                getContentResolver().notifyChange(selectedImage, null);
                reducedSizeBitmap = getBitmap(imageToUploadUri.getPath());
                if(reducedSizeBitmap != null){
                    ImgPhoto.setImageBitmap(reducedSizeBitmap);
                    RobotoTextView uploadImageButton = (RobotoTextView) findViewById(R.id.uploadUserImageButton);
                    uploadImageButton.setVisibility(View.VISIBLE);
                }else{
                    Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
                }
            }else{
                Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
            }
        }
    }

    private void uploadImage(boolean profilePhoto) {
        if(!(reducedSizeBitmap == null)){
            if(reducedSizeBitmap == null){
                Log.d("Image bitmap"," Is null");
            }
            reducedSizeBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
            byte[] byteArray = stream.toByteArray();
            this.restaurantService.addRestaurantImage(byteArray,profilePhoto);
        }
    }
}

我希望这多的信息就足够了。任何人都可以点我它的功能,我应该放哪里。非常感谢。 : - )

I hope this much information is enough. Can anyone point me which functions I should put and where. Thanks a lot. :-)

编辑使用答案

最后的整合工作。我不得不从答案我收到上SO 一个结合。
最后code

Finally the integration works. I had to combine answers from the one I received and here on SO. Final Code

public class AddPhotosForRestaurant extends RestaurantDrawerActivity {

    RobotoTextView BtnSelectImage;
    private ImageView ImgPhoto;

    CheckBox profilePhotoCheckBox;
    final RestaurantImageServiceImpl restaurantService = new RestaurantImageServiceImpl();

    private static final int CAMERA_PHOTO = 111;
    public static final int GALLERY_INTENT_REQUEST_CODE = 0x000005;
    private Uri imageToUploadUri = null;

    private static volatile Bitmap reducedSizeBitmap;

    ByteArrayOutputStream stream = new ByteArrayOutputStream();

    private boolean galleryFlag = false;

    private boolean uploadNow = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_restaurant_images);

        set(null, null);

        final RobotoTextView uploadImageButton = (RobotoTextView) findViewById(R.id.uploadUserImageButton);

        ImgPhoto = (ImageView) findViewById(R.id.userPhotoImageView);
        BtnSelectImage = (RobotoTextView) findViewById(R.id.userPhotoButtonSelect);
        profilePhotoCheckBox = (CheckBox) findViewById(R.id.profilePhotoCheckBox);
        BtnSelectImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    galleryFlag = true;
                    captureCameraImage();

                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(), "Couldn't load photo", Toast.LENGTH_LONG).show();
                }
            }
        });

        uploadImageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!(v == null)) {

                    if (uploadNow) {
                        uploadNow = false;
                        galleryFlag = true;
                        if (profilePhotoCheckBox.isChecked()) {
                            uploadImage(true);
                        } else {
                            uploadImage(false);
                        }
                    }

                    if (!galleryFlag) {
                        galleryFlag = true;
                        uploadNow = true;
                        Intent intent = new Intent();
                        intent.setType("image/*");
                        intent.setAction(Intent.ACTION_GET_CONTENT);
                        startActivityForResult(Intent.createChooser(intent, "Select Picture"),
                                GALLERY_INTENT_REQUEST_CODE);
                    } else {
                        if (profilePhotoCheckBox.isChecked()) {
                            uploadImage(true);
                        } else {
                            uploadImage(false);
                        }
                        new AlertDialog.Builder(AddPhotosForRestaurant.this)
                                .setTitle("Add more photos")
                                .setMessage("Are you sure you want to add more photos?")
                                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        finish();
                                        startActivity(getIntent());
                                    }
                                })
                                .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        Intent intent = new Intent(getApplicationContext(), RestaurantMenu.class);
                                        startActivity(intent);
                                        finish();
                                    }
                                })
                                .setIcon(android.R.drawable.ic_dialog_alert)
                                .show();
                    }

                }
            }
        });

    }

    private Bitmap getBitmap(String path) {

        Uri uri = Uri.fromFile(new File(path));
        InputStream in = null;
        try {
            final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
            in = getContentResolver().openInputStream(uri);

            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(in, null, o);
            in.close();


            int scale = 1;
            while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) >
                    IMAGE_MAX_SIZE) {
                scale++;
            }
            Bitmap b;
            in = getContentResolver().openInputStream(uri);
            if (scale > 1) {
                scale--;
                // scale to max possible inSampleSize that still yields an image
                // larger than target
                o = new BitmapFactory.Options();
                o.inSampleSize = scale;
                b = BitmapFactory.decodeStream(in, null, o);

                // resize to desired dimensions
                int height = b.getHeight();
                int width = b.getWidth();

                double y = Math.sqrt(IMAGE_MAX_SIZE
                        / (((double) width) / height));
                double x = (y / height) * width;

                Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x,
                        (int) y, true);
                b.recycle();
                b = scaledBitmap;
                System.gc();
            } else {
                b = BitmapFactory.decodeStream(in);
            }
            in.close();
            return b;
        } catch (IOException e) {
            return null;
        }
    }

    private void captureCameraImage() {
        Intent chooserIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File f = new File(Environment.getExternalStorageDirectory(), "POST_IMAGE.jpg");
        chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
        imageToUploadUri = Uri.fromFile(f);
        startActivityForResult(chooserIntent, CAMERA_PHOTO);
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent(this, Login.class);
        StaticRestTemplate.setReplyString("");
        StaticRestTemplate.setLoggedInUser("");
        StaticRestTemplate.setJsessionid("");
        startActivity(intent);
        finish();
    }

    @Override
    protected void onActivityResult(final int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == CAMERA_PHOTO && resultCode == Activity.RESULT_OK) {
            if (imageToUploadUri != null) {
                Uri selectedImage = imageToUploadUri;
                getContentResolver().notifyChange(selectedImage, null);
                reducedSizeBitmap = getBitmap(imageToUploadUri.getPath());
                if (reducedSizeBitmap != null) {
                    ImgPhoto.setImageBitmap(reducedSizeBitmap);
                    RobotoTextView uploadImageButton = (RobotoTextView) findViewById(R.id.uploadUserImageButton);
                    uploadImageButton.setVisibility(View.VISIBLE);
                } else {
                    Toast.makeText(this, "Error while capturing Image", Toast.LENGTH_LONG).show();
                }
            } else {
                Toast.makeText(this, "Error while capturing Image", Toast.LENGTH_LONG).show();
            }
        }

        if (requestCode == GALLERY_INTENT_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            try {
                Uri selectedImage = Uri.parse(data.getDataString());

                reducedSizeBitmap = MediaStore.Images.Media.getBitmap(
                        getApplicationContext().getContentResolver(),
                        selectedImage);
                ImgPhoto.setImageBitmap(reducedSizeBitmap);

            } catch (Exception e) {
                Toast.makeText(this, "Error while selecting Image", Toast.LENGTH_LONG).show();
            }
        }
    }

    private void uploadImage(boolean profilePhoto) {

        if (!(reducedSizeBitmap == null)) {
            reducedSizeBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
            byte[] byteArray = stream.toByteArray();
            this.restaurantService.addRestaurantImage(byteArray, profilePhoto);
        }
    }
}

非常感谢你的帮助..: - )

Thanks a lot for all your help.. :-)

推荐答案

在恒文件的写在我的情况(ActivityConstantUtils.java)

In Constant file write in my case(ActivityConstantUtils.java)

public static final int GALLERY_INTENT_REQUEST_CODE = 0x000005;

要开画廊及放大器;获得所选图像使用路径跟踪code:

To open Gallery & get path of selected image use following code :

 Intent photoPickerIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
 photoPickerIntent.setType("image/*");
 photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());        
 mActPanelFragment.startActivityForResult(photoPickerIntent, ActivityConstantUtils.GALLERY_INTENT_REQUEST_CODE);

之后,你得到的的onActivityResult()方法路径

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
(requestCode == ActivityConstantUtils.GALLERY_INTENT_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
try {
            String imagePath = getFilePath(data);
            // TODO: Here you set data to preview screen
    }catch(Exception e){}
}

}

private String getFilePath(Intent data) {
    String imagePath;
    Uri selectedImage = data.getData();
    String[] filePathColumn = {MediaStore.Images.Media.DATA};

    Cursor cursor = getActivity().getContentResolver().query(selectedImage, filePathColumn, null, null, null);
    cursor.moveToFirst();

    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
    imagePath = cursor.getString(columnIndex);
    cursor.close();

    return imagePath;

}

这篇关于安卓:用摄像头采集集成库功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆