ThePartyTurtle February 2016

Image URL to ParseFile?

I have a Parse Android app for which I am implementing Facebook sign up. Currently I am stuck on grabbing images to set as profile pictures of new ParseUser's. I have successfully used the Facebook Graph API to retrieve the correct URL (I have checked this by plugging it into a browser, where I am shown the right profile picture), but I now need a way to turn that URL into a byte array (byte[]) so that I can save the ParseFile field of our ParseUser's profile picture. I have already looked at all these SO questions:

java.net.URL read stream to byte[]

Efficiently read file from URL into byte[] in Java

Get image with given url and convert it to byte array

None of these have worked. I am currently trying to use the Apache IOutils, like in the solution from the second link. Here is my current code for the AsyncTask:

private class SetProfPicWithURL extends AsyncTask<URL, Integer, byte[]> {
        @Override
        protected byte[] doInBackground(URL... imageURL) {
            Log.i("SetProfPicWithURL", "invocation, URL: " + imageURL[0]);
            InputStream is = null;
            byte[] bytes = null;
            try {
                is = imageURL[0].openStream();
                bytes = IOUtils.toByteArray(is);
            } catch (IOException e) {
                e.printStackTrace();
            }
            finally {
                if (is != null) try {
                    is.close();

                    if(bytes == null){Log.e("LoginActivity", "bytes is null int SetProfPicWithURL");}
                    final ParseFile imageFile = new ParseFile("image.jpg", bytes);
                    ima        

Answers


ved February 2016

Directly save your imagefile as profile picture like this :

final ParseFile imageFile = new ParseFile("image.jpg", bytes);
ParseUser.getCurrentUser().put(ParseUtils.PARSE_PROFILE_IMAGE, imageFile);
ParseUser.getCurrentUser().saveInBackground(new SaveCallback() {
    @Override
    public void done(ParseException e) {
        if (e == null) {
            Log.i("LoginActivity", "Profile saved succesfully");

        } else {
            e.printStackTrace();
        }
    }
});

EDIT :

Use this to get image byte array from url.

try {
    java.net.URL img_value = new java.net.URL(imageURL);        
    Bitmap mIcon = BitmapFactory
            .decodeStream(img_value.openConnection()
                    .getInputStream());
    if (mIcon != null)
        imgByteArray = encodeToByteArray(mIcon);
} catch (Exception e) {
    e.printStackTrace();
}


public byte[] encodeToByteArray(Bitmap image) {
    Log.d(TAG, "encodeToByteArray");
    Bitmap b= image;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    b.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] imgByteArray = baos.toByteArray();

    return imgByteArray ;
}

Post Status

Asked in February 2016
Viewed 1,004 times
Voted 6
Answered 1 times

Search




Leave an answer