Thursday 8 August 2013

Display Image with adding Overlay

write below code in your xml file

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/splashscreenbg"
    android:orientation="vertical" >

    <ScrollView
        android:id="@+id/scrollingmain"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_below="@+id/include1"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="10dp"
        android:paddingLeft="10dp"
        android:paddingRight="10dp" >

        <TableLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dip" >

            <TableRow
                android:id="@+id/angletakephoto"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="1dip"
                android:layout_marginLeft="20dp"
                android:layout_marginRight="20dp"
                android:clickable="true"
                android:gravity="center"
                android:paddingTop="20dp" >

                <Button
                    android:id="@+id/buttonphoto"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="10dp"
                    android:layout_weight="1"
                    android:background="@drawable/savebtnselector"
                    android:onClick="takePhotoClick"
                   android:layout_gravity="center_vertical"
                    android:text="@string/btnphoto"
                    android:textColor="#ffffff" />

                <TextView
                    android:id="@+id/Text"
                    android:layout_width="15dp"
                    android:layout_height="wrap_content" />

                <Button
                    android:id="@+id/buttonphotofromlibrary"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginRight="10dp"
                    android:layout_weight="1"
                    android:background="@drawable/savebtnselector"
                    android:onClick="takePhotofromLibraryClick"
                     android:layout_gravity="center_vertical"
                    android:text="@string/btnphotofromlib"
                    android:textColor="#ffffff" />
            </TableRow>

            <TableRow
                android:id="@+id/anglephoto"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="1dip"
                android:layout_marginTop="10dp"
                android:clickable="true"
                android:gravity="center" >

                <FrameLayout
                    android:layout_width="match_parent"
                    android:layout_height="fill_parent"
                    android:layout_marginBottom="5dp"
                    android:layout_gravity="center_horizontal">

                    <ImageView
                        android:id="@+id/imageViewphoto"
                        android:layout_width="290dp"
                        android:layout_height="300dp"
                        android:adjustViewBounds="true"
                        android:layout_gravity="center"
                        android:src="@drawable/defaultprofileimg" />

                </FrameLayout>
            </TableRow>
        </TableLayout>
    </ScrollView>

</RelativeLayout>



in your main Activity 

public void takePhotoClick(View view) {
        PackageManager pm = getPackageManager();
        if (pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
            File mFile = new File(Environment.getExternalStorageDirectory() + "/My_images");
            if(!mFile.exists()) {
                mFile.mkdirs();
            }
            mFile = new File(mFile.getAbsolutePath() + "/temp.jpg");
            Intent i = new Intent(
                    android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mFile));
            startActivityForResult(i, CAMERA_RESULT);

        } else {
            Toast.makeText(getBaseContext(), "Camera is not available",
                    Toast.LENGTH_LONG).show();
        }

    }

    public void takePhotofromLibraryClick(View view) {
        Intent i = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(i, RESULT_LOAD_IMAGE);

    }


    private void loadAndDisplayImage(File mFile) {
        new AsyncTask<File, Void, Bitmap>() {
            byte[] bitmapdata;
            ProgressDialog pbr;

            protected void onPreExecute() {
                System.gc();
                pbr = new ProgressDialog(SaveAngle.this);
                pbr.setMessage("Loading...");
                pbr.show();
            };

            @Override
            protected Bitmap doInBackground(File... params) {
                Bitmap mBitmap = Utility.decodeFile(params[0], 256);

                if(mBitmap != null) {
                    try {
                        Bitmap result = Bitmap.createBitmap(mBitmap.getWidth(), mBitmap.getHeight(), Bitmap.Config.ARGB_8888);
                        Bitmap withstring = getThumb("name", "title", mBitmap.getWidth() + 50, mBitmap.getHeight()/6);
                        Canvas c = new Canvas(result);
                        c.drawBitmap(mBitmap, 0f, 0f, null);
                        c.drawBitmap(withstring, 0f, mBitmap.getHeight()-(mBitmap.getHeight()/6), null);
                       
                        ByteArrayOutputStream stream = new ByteArrayOutputStream();
                        result.compress(Bitmap.CompressFormat.JPEG, 90, stream);
                        bitmapdata = stream.toByteArray();

                        if (bitmapdata != null) {
                            MyWrite(bitmapdata);
                        }
                        mBitmap.recycle();
                        mBitmap = null;
                        System.gc();
                        return result;
                    } catch (Exception e) {
                        e.printStackTrace();
                        return null;
                    }
                }
                return null;
            }

            protected void onPostExecute(Bitmap result) {
                if (result != null) {
                    if(pbr != null && pbr.isShowing()) {
                        pbr.dismiss();
                    }
                    imguser.setScaleType(ScaleType.CENTER_INSIDE);
                    imguser.setImageBitmap(result);
                }
            };
        }.execute(mFile);
    }
   
    @Override
    protected void onActivityResult(int requestCode, int resultCode,
            final Intent data) {

        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
                && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver()
                    .query(selectedImage, filePathColumn, null,
                            null, null);
            cursor.moveToFirst();
            int columnIndex = cursor
                    .getColumnIndex(filePathColumn[0]);
            picturePath = cursor.getString(columnIndex);
            //strimagepath = picturePath;
            File f = new File(picturePath);
            strimagepath = f.getAbsolutePath();
            loadAndDisplayImage(f);
        }

        if (resultCode == RESULT_OK && requestCode == CAMERA_RESULT) {
           
            final File mFile = new File(Environment.getExternalStorageDirectory() + "/My_images/temp.jpg");
            if(!mFile.exists()) {
                Toast.makeText(getBaseContext(), "Image not captured successfully.", Toast.LENGTH_SHORT).show();
                return;
            }
            strimagepath = mFile.getAbsolutePath();
            loadAndDisplayImage(mFile);
        }
    }

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



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

        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
                && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver()
                    .query(selectedImage, filePathColumn, null,
                            null, null);
            cursor.moveToFirst();
            int columnIndex = cursor
                    .getColumnIndex(filePathColumn[0]);
            picturePath = cursor.getString(columnIndex);
            //strimagepath = picturePath;
            File f = new File(picturePath);
            strimagepath = f.getAbsolutePath();
            loadAndDisplayImage(f);
        }

        if (resultCode == RESULT_OK && requestCode == CAMERA_RESULT) {
           
            final File mFile = new File(Environment.getExternalStorageDirectory() + "/My_images/temp.jpg");
            if(!mFile.exists()) {
                Toast.makeText(getBaseContext(), "Image not captured successfully.", Toast.LENGTH_SHORT).show();
                return;
            }
            strimagepath = mFile.getAbsolutePath();
            loadAndDisplayImage(mFile);
        }
    }




    public void MyWrite(byte[] buffer) {
        System.gc();
        File sdCard = Environment.getExternalStorageDirectory();
        File directory = new File(sdCard.getAbsolutePath() + "/MyAngleImage");
        directory.mkdirs();
        // Now create the file in the above directory and write the contents
        // into it
        System.out.println("Image path=" +strimagepath);
        File file;
        file = new File(directory, currentDateandTime);

        // File file = new File(directory, "sample.jpg");
        strimagepath = file.getAbsolutePath();
        System.out.println("Path=" + strimagepath);
       
        try {
            if(!file.exists())
            file.createNewFile();
        } catch (IOException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        }
       
       
        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(file);
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        BufferedOutputStream osw = new BufferedOutputStream(fOut);
        try {
            // osw.write(path);
            osw.write(buffer);
            // osw.write(buffer, offset, length);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            osw.flush();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            osw.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }



private Bitmap getThumb(String strangle, String strnote, int width, int height) {

        //Bitmap mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.transperet_bg);
        Bitmap bmOverlay = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);

        Canvas canvas = new Canvas(bmOverlay);
        Paint paint = new Paint();

        paint.setColor(Color.WHITE);
        paint.setTextSize(20);
        paint.setFlags(Paint.ANTI_ALIAS_FLAG);
        // if the background image is defined in main.xml, omit this line
        canvas.drawARGB(140, 0, 0, 0);
        //canvas.drawBitmap(mBitmap, 0, 0, null);
        // draw the text and the point
        paint.setTextAlign(Paint.Align.LEFT);
       
        canvas.drawText("Name", 10, 20, paint);
       
        strnote = edtnote.getText().toString();
        if (TextUtils.isEmpty(strnote)) {
            strnote = "Note";
        }
        canvas.drawText(strnote, 10, 50, paint);
        paint.setTextAlign(Paint.Align.RIGHT);
       
        canvas.drawText("name", width-60, 50, paint);
        canvas.drawText("Application name", width-60, 20, paint);
       
        canvas.drawPoint(30.0f, height/2, paint);
        return bmOverlay;
    }




write decodeFile this function in your common class 

public static Bitmap decodeFile(File f, int size) {
         System.out.println("Decoding file");
            try {
                // decode image size
                BitmapFactory.Options o = new BitmapFactory.Options();
                o.inJustDecodeBounds = true;
                BitmapFactory.decodeStream(new FileInputStream(f), null, o);

                // Find the correct scale value. It should be the power of 2.
                //final int REQUIRED_SIZE = 70;
                //final int REQUIRED_SIZE = 300;
                int width_tmp = o.outWidth, height_tmp = o.outHeight;
                int scale = 1;
                while (true) {
                    if (width_tmp / 2 < size || height_tmp / 2 < size)
                        break;
                    width_tmp /= 2;
                    height_tmp /= 2;
                    scale *= 2;
                }

                // decode with inSampleSize
                BitmapFactory.Options o2 = new BitmapFactory.Options();
                o2.inSampleSize = scale;
                return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
            } catch (FileNotFoundException e) {
                System.out.println("Error :: " + e.getMessage());
            }
            return null;
        }



No comments:

Post a Comment

Comments

Find Hours Diffrence in Kotlin

  In Kotlin, determining the difference in hours between two timestamps is a common task, especially in scenarios involving time-based calcu...