Monday, 15 October 2012

Displaying and Saving Image in Sdcard

Hi all.
In this post i am going to discuss how to get an image from any URL and saving an image into sdcard and also capturing the whole screen. Now lets design a small layout as in the capture.
   

The following xml named first_activity.xml is used to design the capture.


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/layoutCapture" >

    <Button
        android:id="@+id/showImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="25dp"
        android:text="Show Image" />

    <Button
        android:id="@+id/saveImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/showImage"
        android:layout_marginLeft="59dp"
        android:layout_toRightOf="@+id/showImage"
        android:text="Save Image" />

    <Button
        android:id="@+id/captureScreen"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/saveImage"
        android:layout_below="@+id/showImage"
        android:layout_marginRight="66dp"
        android:text="Capture Screen" />
    
    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
      android:layout_below="@+id/captureScreen"
        />

</RelativeLayout>


Now as we can see the three buttons the showImage, saveImage, captureScreen  I am going to write three functions which are used to show the image, save the image and capture the Screen.

Lets have a look at the functions : 

"Show the image" function : 
Here the image source is from the URL : http://www.android.com/images/whatsnew/jb-new-logo.png  and the following the function that helps in getting a bitmap from the url that can be used to display the image onto the ImageView.

private Bitmap showImage(String urlStr) {
try {
URL url = new URL(urlStr);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(input);
return bitmap;
} catch (IOException e) {
e.printStackTrace();
Log.e("Exception", e.getMessage());
return null;
}

}

The most important thing here is dont forget to give the internet permission i.e.., <uses-permission android:name="android.permission.INTERNET"  in the manifest file. Here the urlStr is "http://www.android.com/images/whatsnew/jb-new-logo.png" and if we observe the code we are just opening a connection for the url and saying connect. Next we are getting an inputstream so that we can get data from the particular url and finally decoding the input stream to get a Bitmap object.


Function to "save the image" :
The following function is used to save the image in the sdcard

    void saveImage(){
try {
String filename = Environment.getExternalStorageDirectory().toString();
File f = new File(filename ,"myImage.png");
f.createNewFile();
System.out.println("file created " + f.toString());
      FileOutputStream out = new FileOutputStream(f);
      Bitmap bitmap = showImage(urlStr);
      bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
} catch (Exception e) {
      e.printStackTrace();
}
}

Here i am getting the path of the sdcard dynamically using Environment.getExternalStorageDirectory().toString(); and creating a file with a name myImage.png using the statements 
File f = new File(filename ,"myImage.png");
f.createNewFile(); 
Next creating an output stream to that file so that we can save the image to the particular file using 
           bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
Here the second parameter i.e., 90 is the quality parameter which may vary from 0 -100. In case of png format this will be ignored as it is lossless.
here the bitmap is obtained from the previous function showImage(urlStr); 
The most important thing here is dont forget to give the  permission <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" 

Function to "Capture the Screen" :

The below function is to capture the screen. Have a look at the below code : 

 void saveScreenCapture() {

 View v1 = mBtnSave.getRootView();
//relCapture.setDrawingCacheEnabled(true);
Bitmap bm = v1.getDrawingCache();
mImgPreview.setImageBitmap(bm);

}
Here we need to have root access to your device. Some information about this is discussed in the link here . 
If we need to capture a particular layout we can do that using the particular layout too like the below sample .

instead of the lines  

                View v1 = mBtnSave.getRootView();
Bitmap bm = v1.getDrawingCache();

 use 

              mBtnSave.setDrawingCacheEnabled(true);
              Bitmap bm = mBtnSave.getDrawingCache();

The entire code is as below : 


public class FirstActivity extends Activity {
private RelativeLayout relCapture;
private ImageView mImgPreview;
private Button mBtnShow, mBtnSave, mBtnScreenCapture;
String urlStr = "http://www.android.com/images/whatsnew/jb-new-logo.png";
FileOutputStream outStream = null;
Bitmap bitmap = null;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_activity);
mImgPreview = (ImageView) findViewById(R.id.image);
mBtnShow = (Button) findViewById(R.id.showImage);
mBtnSave = (Button) findViewById(R.id.saveImage);
mBtnScreenCapture = (Button) findViewById(R.id.captureScreen);
relCapture = (RelativeLayout) findViewById(R.id.layoutCapture);
mBtnShow.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
final ProgressDialog dialog = ProgressDialog.show(
FirstActivity.this, "", "Loading...please wait");

new Thread(new Runnable() {
@Override
public void run() {
final Bitmap bitmap = showImage(urlStr);
runOnUiThread(new Runnable() {
@Override
public void run() {

if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
mImgPreview.setImageBitmap(bitmap);

}
}
});
}
}).start();

}
});

mBtnSave.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
// save_Image_to_sdcard();
saveImage();
}
});
mBtnScreenCapture.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
saveScreenCapture();
}
});

}

void saveScreenCapture() {
                View v1 = mBtnSave.getRootView();
v1.setDrawingCacheEnabled(true);
                Bitmap bm = relCapture.getDrawingCache();
               mImgPreview.setImageBitmap(bm);

}

void saveImage() {

try {
String filename = Environment.getExternalStorageDirectory()
.toString();

File f = new File(filename, "1111.png");
f.createNewFile();
System.out.println("file created " + f.toString());
FileOutputStream out = new FileOutputStream(f);
Bitmap bitmap = showImage(urlStr);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
} catch (Exception e) {
e.printStackTrace();
}

}
private Bitmap showImage(String urlStr) {
try {
URL url = new URL(urlStr);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(input);
return bitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}

}
}
The following is the capture obtained when storing the image into the sdcard 
    



Any suggestions are welcomed.

Please comment if anyone has some or the other problem with this one.




3 comments: