lundi 20 juin 2016

How can i save the picture on image view after clicking via camera?

I am making an android app I need to save a picture after clicking, suppose I click an image, then the image will save and appeared on image view after that when I click again a picture then the first picture will delete automatically and the newest will save. This is my code to run camera:

public class MainActivity extends AppCompatActivity{
    Button b1;
    ImageView iv;
    private static final int CAMERA_REQUEST = 1888;
SharedPreferences myPrefrence;
    String itemNAme;

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

        b1=(Button)findViewById(R.id.button);
        iv=(ImageView)findViewById(R.id.imageView);

        b1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, CAMERA_REQUEST);
            }
        });
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
            Bitmap bp = (Bitmap) data.getExtras().get("data");
            iv.setImageBitmap(bp);

            SharedPreferences.Editor editor = myPrefrence.edit();
            editor.putString("namePreferance", itemNAme);
            editor.putString("imagePreferance", encodeTobase64(bp));
            editor.commit();
        }


    }

    public String encodeTobase64(Bitmap bp ) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bp.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
        byte[] byteArray = byteArrayOutputStream .toByteArray();

        String imageEncoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
        return imageEncoded;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.

        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

Aucun commentaire:

Enregistrer un commentaire