Created
February 27, 2017 09:13
-
-
Save mondoktamas/f65f7e93da10294f4472cb227ca65eaa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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