Last active
May 3, 2018 07:40
-
-
Save fatihsokmen/a7f34778cfa8324b712e88fba345ad32 to your computer and use it in GitHub Desktop.
Okhttp custom request body for resizing and uploading image uri
This file contains hidden or 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
import android.content.Context; | |
import android.graphics.Bitmap; | |
import android.net.Uri; | |
import java.io.IOException; | |
import java.lang.ref.WeakReference; | |
import co.wardrope.android.util.BitmapResize; | |
import okhttp3.MediaType; | |
import okhttp3.RequestBody; | |
import okio.BufferedSink; | |
public class ResizeRequestBody extends RequestBody { | |
private WeakReference<Context> contextRef; | |
private Uri uri; | |
private int minWidth; | |
private int minHeight; | |
public ResizeRequestBody(Context context, Uri uri, int minWidth, int minHeight) { | |
this.contextRef = new WeakReference(context); | |
this.uri = uri; | |
this.minWidth = minWidth; | |
this.minHeight = minHeight; | |
} | |
@Override | |
public long contentLength() throws IOException { | |
return -1; | |
} | |
@Override | |
public MediaType contentType() { | |
return MediaType.parse("application/octet-stream"); | |
} | |
@Override | |
public void writeTo(BufferedSink sink) throws IOException { | |
try { | |
Context context = contextRef.get(); | |
if (context != null) { | |
BitmapResize.thumbnail(context, uri, minWidth, minHeight).compress(Bitmap.CompressFormat.JPEG, 75, sink.outputStream()); | |
} | |
} finally { | |
contextRef.clear(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment