Skip to content

Instantly share code, notes, and snippets.

@mondoktamas
Created February 27, 2017 09:13
Show Gist options
  • Save mondoktamas/f65f7e93da10294f4472cb227ca65eaa to your computer and use it in GitHub Desktop.
Save mondoktamas/f65f7e93da10294f4472cb227ca65eaa to your computer and use it in GitHub Desktop.
package com.appinstitute.beau.core.domain;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import com.appinstitute.beau.core.domain.base.BackgroundUseCase;
import java.io.ByteArrayOutputStream;
import javax.inject.Inject;
import rx.Observable;
public class ImageToBase64UseCase extends BackgroundUseCase {
private String mImageFilePath;
@Inject
public ImageToBase64UseCase() { }
public void setImageFilePath(final String imageFilePath) {
mImageFilePath = imageFilePath;
}
@Override
protected Observable buildObservableTask() {
return Observable.just(mImageFilePath)
.map(imageFilePath -> getBitmapFromFile(imageFilePath, 800))
.map(this::convertBitmapToBase64String);
}
private Bitmap getBitmapFromFile(final String imageFilePath,
final int value) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imageFilePath, options);
options.inSampleSize = calculateInSampleSize(options, value);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(imageFilePath, options);
}
private int calculateInSampleSize(final BitmapFactory.Options options,
final int value) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > value || width > value)
inSampleSize = Math.round(Math.min((float) height / value, (float) width / value));
return inSampleSize;
}
private String convertBitmapToBase64String(final Bitmap imageBitmap) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 50, outputStream);
return Base64.encodeToString(outputStream.toByteArray(), Base64.DEFAULT);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment