Skip to main content

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.




Comments

Post a Comment

Popular posts from this blog

Image Slide Show

Hi everyone. In this tutorial i am going to show you all the code which when run will display the images as a slideshow. Below is the attached screen shot :  For this i am considering the images from the Sdcard's images folder where i am having all the images. Next to display the images i am using View Flipper concept. I am adding ImageViews to the viewflipper so that the images can be displayed onto the screen. Now lets start  Design an xml layout as below (say main.xml) <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent" >     <ViewFlipper         android:id="@+id/main_flipper"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_alignParentLeft="true"  

Template literals

Template literals: ES6   introduced many cool things among which one is ‘ Template literals ’   This is a new way of representing strings.    Normally we use either “(double quotes) or ‘(single quote) to represent a string in  JavaScript .   For example:   var name=”literal”;   Or    var name=’literal’;   But from ES6 there is a new way of doing it. We can use `(back tick) symbol which is present left to key ‘1’ in keyboard.    Ie.,   var name = `literal`;   Well when we already have “(double quotes) or ‘(single quote), what extra does `(back tick) do?   Template literals  shines well when we have some concatenation of strings or when creating multi-line strings.   Look at below to understand the power of Template literals.   Let's  take an example where we need to form a string where you are forming a string based on a button clicked. For example - “You clicked on login button”.     Old way:   var 

Localization using .ttf files

In my previous post  here  i gave some information on how to use the concept of localization for the languages that are supported by Android. Now suppose if u want to display a language that is not supported by android.......? Then what might be solution? I will be discussing a small example for doing this now. Suppose if you want to display some text like this " हिंदी " or  " தமிழ் " or  some thing like the text   here  any other language that is  not supported by android we can use .ttf files so that we can print the font we are interested. To achieve this first we need to download few .ttf files. You can google for a file you need, download it and place this into the assets folder. In the picture i am having few other ttf files which i included, But for the time being only the DroidSansRegionalAAd.ttf is discussed by me which i used to display the words of few languages of India as in the following picture. Now we need to refer to the ttf file i