Friday, 23 January 2015

Image Transaction in Android from Device To Server

Hi!

     Today lot of developer facing problem while  saving and retrieving images in Android from Device To Server and vice versa.

 This blog will be help you to solve this issue.

Step 1 :
call the gallery to select the image

Step 2 :
By using ActivityResultSet() we can receive the image

Step 3 :
Compress the image and convert into string

Code:

ImageView imv_tst_img;   // to set the output of the image
private static Bitmap Image = null; // Bitmap for handle the image compression
Button btn_rg_image;     // for action purpose
String Image_sv;           // to store the image as string

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rg__name);
imv_tst_img=(ImageView) findViewById(R.id.imv_tst_img);
btn_rg_image=(Button) findViewById(R.id.btn_rg_image);

btn_rg_image.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
imv_tst_img.setImageBitmap(null);
if (Image != null)
Image.recycle();
Intent intent = new Intent();
intent.setType("image/*");

// to call the Gallery intent
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Select Picture"), GALLERY);
}
});
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == GALLERY && resultCode != 0) {
Uri mImageUri = data.getData();
try {
// create the Bitmap by using the selected image
Image = Media.getBitmap(this.getContentResolver(), mImageUri);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
Bitmap bit_map = Bitmap.createBitmap(Image, 0, 0,
Image.getWidth(), Image.getHeight());
//compress the bitmap
bit_map.compress(Bitmap.CompressFormat.JPEG, 75, bao);
//converted as byte[] array
byte[] byt_ara = bao.toByteArray();
// Encode by Base64 and save as string
String encoded_btmp = Base64
.encodeToString(byt_ara, Base64.DEFAULT);
// in mycode i pass the string for public use
Image_sv = encoded_btmp;
Log.d("Image_Save", Image_sv);
System.out.println("Image _1 : "+Image_sv);

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

// Revers Process : method to convert the string into Bitmap and set it on the ImageViewer
public void set_Image() {
try {
byte[] decodedString = Base64.decode(Image_sv, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString,
0, decodedString.length);
imv_tst_img.setImageBitmap(decodedByte);
} catch (Exception e) {
// TODO: handle exception
Log.d("ERROR ON IMG", e.getMessage());
}
}

Thats All..,

Thank You!

Please Leave Your Comment..,


Have A Happy Day..,

No comments:

Post a Comment