简体   繁体   中英

Save string as an image on device internal storage

I'm developing an Android app that connects to facebook and save user's profile image on device internal storage.

This is my code:

private void getFacebookUserProfilePicture(String userAccessToken)
{
    String url = Constants.FB_PROFILE_IMAGE_URL + userAccessToken;

    AsyncHttpClient client = new AsyncHttpClient();
    client.get(url, new AsyncHttpResponseHandler()
    {
        @Override
        public void onSuccess(String response)
        {
            saveUserProfileImage(response.getBytes());
        }
    });
}
private void saveUserProfileImage(byte[] imageBytes)
{
    Log.v(TAG, "Save user image");

    FileOutputStream fOut = null;
    try
    {
        fOut = openFileOutput(Constants.FB_PROFILE_IMAGE_FILE_NAME, Context.MODE_PRIVATE);

        fOut.write(imageBytes);
        fOut.close();
    }
    catch (IOException ioe)
    {
        ioe.printStackTrace();
    }
}

I'm testing using Android emulator and I have used Eclipse DDMS to save the file to my PC, but I can't open it.

What am I doing wrong? I have saved with a jpg extension.

Or maybe, the question could be: How can I save a byte[] as a JPG image?

If I test the url on the browser, I get an image with 2,47KB . And the image I have copied from the device is 4,26KB .

you can follow this link . And after that you can check if it's loading image from device or not.

You can convert string into byte array and then write this array to your filename. You this method to write array:

public void WriteByteToFile(byte[] mybytes, String filename){

try {

FileOutputStream FOS = openFileOutput(filename, MODE_PRIVATE);
FOS.write(mybytes);
FOS.close();


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

}

Convert string into byte array like below:

byte[] bytes = string.getBytes("UTF-8");

Try it hopr this solve your problem..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM