Showing posts with label Image. Show all posts
Showing posts with label Image. Show all posts

Tuesday, March 8, 2016

Select Image from Gallery or Capture through Camera and Store it in shared preferences and use it inside application in Android

First you need to convert image to Base64 String representation and then store it in shared 
preference as follows :

Bitmap realImage = BitmapFactory.decodeStream(stream);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
realImage.compress(Bitmap.CompressFormat.JPEG, 100, baos);   
byte[] b = baos.toByteArray(); 

String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);

textEncode.setText(encodedImage);

SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this);

Editor edit=shre.edit();
edit.putString("image_data",encodedImage);
edit.commit();

and you can retrieve the image using Bitmap as :


SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this);
String previouslyEncodedImage = shre.getString("image_data", "");

if( !previouslyEncodedImage.equalsIgnoreCase("") ){

    byte[] b = Base64.decode(previouslyEncodedImage, Base64.DEFAULT);
    Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);
    imageView.setImageBitmap(bitmap);
}

if You are using capturing image with camera or picking up from galleryin both way you can use this methods as :

private static final int CAPTURE_IMAGE = 0;
private static final int SELECT_PICTURE = 1;

and then implement this method :


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

    if (requestCode == CAPTURE_IMAGE) {
        Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
        storeImage(thumbnail);
    } else if (requestCode == SELECT_PICTURE) {
        Uri mImageUri = data.getData();
        Bitmap thumbnail = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), mImageUri);
        storeImage(thumbnail);
    }
}

and store Image method is as follows :

private void storeImage(Bitmap thumbnail) {

    // Removing image saved earlier in shared prefernces
    shre = PreferenceManager.getDefaultSharedPreferences(getActivity());
    SharedPreferences.Editor edit=shre.edit();
    edit.remove("image_data");
    edit.commit();

    ByteArrayOutputStream bytes = new ByteArrayOutputStream();

    thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    File destination = new File(Environment.getExternalStorageDirectory(),
            System.currentTimeMillis() + ".jpg");
    FileOutputStream fo;
    try {
        destination.createNewFile();
        fo = new FileOutputStream(destination);
        fo.write(bytes.toByteArray());
        fo.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    imageview.setImageBitmap(thumbnail);
    byte[] b = bytes.toByteArray();
    String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
    //saving image to shared preferences
    edit.putString("image_data",encodedImage);
    edit.commit();
}

Saturday, March 5, 2016

Crop An Image in Android Programmatically


package zafar.android.cropimage;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.<span id="IL_AD8" class="IL_AD">Paint</span>;
import android.graphics.Path;
import android.graphics.<span id="IL_AD9" class="IL_AD">Rect</span>;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.AbsoluteLayout;
import android.widget.FrameLayout;
@SuppressWarnings({ "deprecation", "<span id="IL_AD10" class="IL_AD">unused</span>" })
public class Move extends Activity {
    public FrameLayout board;
    public View part1;
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
         board = new FrameLayout(this);
         board = (FrameLayout)findViewById(R.id.Board);
         part1 = <span id="IL_AD7" class="IL_AD">new View</span>(this);
         part1 = findViewById(R.id.part1);
        try{
            Paint paint = new Paint();
            paint.setFilterBitmap(true);
            Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),R.drawable.image);
            int targetWidth  = 300;
            int targetHeight = 300;
            Bitmap targetBitmap = Bitmap.createBitmap(targetWidth, targetHeight,Bitmap.<span id="IL_AD2" class="IL_AD">Config</span>.ARGB_8888);
            RectF rectf = new RectF(0, 0, 100, 100);
            Canvas canvas = new Canvas(targetBitmap);
            Path path = new Path();
            path.addRect(rectf, Path.Direction.CW);
            canvas.clipPath(path);
            canvas.drawBitmap( bitmapOrg, new Rect(0, 0, bitmapOrg.getWidth(), bitmapOrg.getHeight()),
                            new Rect(0, 0, targetWidth, targetHeight), paint);
            <span id="IL_AD5" class="IL_AD">Matrix matrix</span> = <span id="IL_AD6" class="IL_AD">new Matrix</span>();
            matrix.postScale(1f, 1f);
            Bitmap resizedBitmap = Bitmap.createBitmap(targetBitmap, 0, 0, 100, 100, matrix, true);
            /*convert Bitmap to resource */
            BitmapDrawable bd = new BitmapDrawable(resizedBitmap);
            part1.setBackgroundDrawable(bd);
        }
        catch(Exception e){
            System.out.println("Error1 : " + e.getMessage() + e.toString());
      }
    }
main.xml
<?<span id="IL_AD11" class="IL_AD">xml version</span>="1.0" encoding="utf-8"?>
<FrameLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     android:id="@+id/Board"
     android:layout_gravity="top">
<View
        android:layout_height="100dp"
        android:layout_width="100dp"
        android:id="@+id/part1"
        >
</FrameLayout>


For further any exception, Let me know..