2

I need help in improving my code .

What I am doing : There is a button in main activity, when clicked , user choose the image , after that, the image is passed through an intent to another activity(add_image.java) and displayed in an image view , after that I send the image to the server.

My problems:1) I want the best way to send the path image to second intent then convert it into image
2) then compress it as much as I can without loosing a lot of its quality. the image size now is 376kb . so in my my app Ill displaying several images so in such size it will consume time and internet to load.( I am using picasso and fit() didnt decrease the size.)

here is my code :

  @Override
       protected void onActivityResult(int requestCode, int resultCode, Intent data) {

           super.onActivityResult(requestCode, resultCode, data);

            if (requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null) {

                //file name
                filePath = data.getData();
                try {
                //  Bundle extras2 = data.getExtras();
                    bitmap  = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                    ByteArrayOutputStream stream = new ByteArrayOutputStream();               
                   byte imageInByte[] = stream.toByteArray();                    
                  Intent i = new Intent(this, AddImage.class);
                  i.putExtra("image", imageInByte);
                  startActivity(i);
                } catch (IOException e) {
                    e.printStackTrace();     }   }   }    

And here I am receiving the image

     byte[] byteArray = getIntent().getByteArrayExtra("image");
            encodedImage = Base64.encodeToString(byteArray, Base64);
            bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
          ImageView imageview = (ImageView) findViewById(R.id.imageView);
            imageview.setImageBitmap(bmp);
Moudiz
  • 6,775
  • 18
  • 67
  • 139
  • 1
    try this link http://stackoverflow.com/a/20824141/3678308 – Muhammad Waleed Sep 13 '15 at 17:03
  • 1) Try to send the path to the second activity where you will show the image in the imageview. Path could be send to the second activity via intent usning putExtra(KEY, PATH_OF_IMAGE) On reciving the path on the add_image_activity, you could use the path to load the image. 2) To compress you could check [this](http://stackoverflow.com/questions/18545246/how-to-compress-image-size) link. – avinash Sep 16 '15 at 10:47
  • @avinash I tried to do that but it didnt work http://stackoverflow.com/questions/32584648/how-to-send-from-onactivityresult-uri-path-to-another-activity-and-change-it-to – Moudiz Sep 16 '15 at 10:50
  • To compress the image you could use this [link](http://stackoverflow.com/questions/28424942/decrease-image-size-without-losing-its-quality-in-android) or [link](http://stackoverflow.com/questions/477572/strange-out-of-memory-issue-while-loading-an-image-to-a-bitmap-object/823966#823966). Once the image is compresed you could show the image in the imageview. – avinash Sep 16 '15 at 11:00
  • @avinash thanks for the link ill check them – Moudiz Sep 16 '15 at 11:15
  • @avinash I am still facing problem with first step can you offer a link or an example ? how to pass uri intent to another activitty – Moudiz Sep 19 '15 at 05:25
  • @Moudiz : The link you provided for the image is not working , could you please update the link. – avinash Sep 19 '15 at 10:24

1 Answers1

1

Try following code, you might need to modify some of the parameters as per your requirement :

Create MainActivity as following :

public class MainActivity extends Activity implements OnClickListener {
private final int REQUEST_IMAGE_GALLERY = 2000;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    findViewById(R.id.button).setOnClickListener(this);
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.button:
        pickImageFromGallery();
        break;

    default:
        break;
    }
}

private void pickImageFromGallery() {
    Intent intent = new Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    intent.setType("image/*");
    startActivityForResult(Intent.createChooser(intent, "Select File"),
            REQUEST_IMAGE_GALLERY);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode != Activity.RESULT_OK) {
        return;
    }

    if (requestCode == REQUEST_IMAGE_GALLERY) {
        Uri selectedImageUri = data.getData();

        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(selectedImageUri,
                filePathColumn, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();

        Log.e("PATH", "" + picturePath);
        Intent intent = new Intent(this, AddImage.class);
        intent.putExtra("PATH", picturePath);
        startActivity(intent);

    }
}
}

Now create activity_main.xml as follows :

<LinearLayout 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" >

<Button
    android:id="@+id/button"
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="ChooseButton" />

    </LinearLayout>

Then we need to create AddImage activity as follows :

public class AddImage extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.add_image);
    ImageView imageView = (ImageView) findViewById(R.id.image_view);
    if (getIntent() != null) {
        String path = getIntent().getStringExtra("PATH");
        Log.e("PATHR", "" + path);
        new BitmapWorkerTask(imageView).execute(path);
    }

}

private boolean isNeedToBeScaled(String path) {
    File file = new File(path);

    if (file.length() > (1024 * 1024) && isExist(path)) {
        Log.e("SCALEIMAGE", "SACLE");
        return true;
    }
    return false;
}

private boolean isExist(String path) {
    File file = new File(path);
    return file.exists();
}

private Bitmap getScaledImage(String path) {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(path, options);

    int srcWidth = options.outWidth;
    int srcHeight = options.outHeight;
    int[] newWH = new int[2];
    newWH[0] = srcWidth / 2;
    newWH[1] = (newWH[0] * srcHeight) / srcWidth;

    int inSampleSize = 2;
    while (srcWidth / 2 >= newWH[0]) {
        srcWidth /= 2;
        srcHeight /= 2;
        inSampleSize *= 2;

        options.inJustDecodeBounds = false;
        options.inDither = false;
        options.inSampleSize = inSampleSize;
        options.inScaled = false;
        options.inPreferredConfig = Bitmap.Config.RGB_565;
    }
    Bitmap sampledSrcBitmap = BitmapFactory.decodeFile(path, options);

    return sampledSrcBitmap;
}

class BitmapWorkerTask extends AsyncTask<String, Void, Bitmap> {
    private final WeakReference<ImageView> imageViewReference;

    public BitmapWorkerTask(ImageView mImageView) {
        imageViewReference = new WeakReference<ImageView>(mImageView);
    }

    @Override
    protected Bitmap doInBackground(String... params) {
        Bitmap scaled = null;
        if (isNeedToBeScaled(params[0])) {
            Bitmap d;

            d = getScaledImage(params[0]);
            int nh = (int) (d.getHeight() * (512.0 / d.getWidth()));
            scaled = Bitmap.createScaledBitmap(d, 512, nh, true);

        } else {
            scaled = BitmapFactory.decodeFile(params[0], null);
        }
        return scaled;

    }

    @Override
    protected void onPostExecute(Bitmap result) {

        if (imageViewReference != null && result != null) {
            final ImageView imageView = imageViewReference.get();
            if (imageView != null) {
                imageView.setImageBitmap(result);
                imageView.setVisibility(View.VISIBLE);

            }
        }
    }

}
}
avinash
  • 1,529
  • 21
  • 33
  • well I was able to do that however ill check your code maybe I can enhance something .. ill accept it however can you please please check this quetios that I have asked now ? http://stackoverflow.com/questions/32669433/uploading-image-not-displaying-however-others-is-displaying – Moudiz Sep 19 '15 at 14:36