I am currently doing android app for plant recognition using machine learning model which is deployed in Heroku. I capture image using camera implemented in my app and I want to send that image into api deployed in heroku, which will then predict the image and send me back the response in a string format which tells us that to which species it belongs to.
public class MainActivity extends AppCompatActivity {
private final int CAMERA_REQ_CODE=100;
private final int GALLERY_REQ_CODE=1000;
ImageView imgCam;
Bitmap img;
String url = "https://medkit.herokuapp.com/predict";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgCam=findViewById(R.id.imgCamera);
Button btnCamera=findViewById(R.id.btnCamera);
Button btnGallery=findViewById(R.id.btnGallery);
Button btnPredict=findViewById(R.id.btnPredict);
TextView result=findViewById(R.id.resultText);
btnCamera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent iCamera=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(iCamera,CAMERA_REQ_CODE);
}
});
btnGallery.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent iGallery=new Intent(Intent.ACTION_PICK);
iGallery.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(iGallery,GALLERY_REQ_CODE);
}
});
btnPredict.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String data = jsonObject.getString("y_pred_mobile");
if (data.equals("1")) {
result.setText("Hibiscus");
} else if (data.equals("2")) {
result.setText("Aloevera");
} else if (data.equals("3")) {
result.setText("Brahmi");
} else if (data.equals("4")) {
result.setText("Neem");
} else {
result.setText("not in the selected species");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void one rrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {@override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String,String>();
params.put("cgpa",cgpa.getText().toString());
params.put("iq",iq.getText().toString());
params.put("profile_score",profile_score.getText().toString());
return params;
}
};
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
queue.add(stringRequest);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==RESULT_OK)
{
if(requestCode==CAMERA_REQ_CODE)
{
//for camera
Bitmap img=(Bitmap)(data.getExtras().get("data"));
imgCam.setImageBitmap(img);
}
if(requestCode==GALLERY_REQ_CODE)
{
//for Gallery
imgCam.setImageURI(data.getData());
}
}
}
} ` above is my app code. Rest all works fine but i need a code that will put image instead of string for example
@Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String,String>();
params.put("cgpa",cgpa.getText().toString());
params.put("iq",iq.getText().toString());
params.put("profile_score",profile_score.getText().toString());
return params;
this code is to send string as a data , I need a code that can send image as data to the api instead of string like in the above code
Can anyone please help me to fix this ?
CodePudding user response:
I assume that you're trying to upload a bitmap image to your Heroku
server. Then the below code sample could help you.
Create a class VolleyMultipartRequest
same as shown below. This class allows MultiPart
files to be sent to the server.
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;
public class VolleyMultipartRequest extends Request<NetworkResponse> {
private final String twoHyphens = "--";
private final String lineEnd = "\r\n";
private final String boundary = "APIClient-" System.currentTimeMillis ();
private final Response.Listener<NetworkResponse> mListener;
private final Response.ErrorListener mErrorListener;
public VolleyMultipartRequest ( int method, String url, Response.Listener<NetworkResponse> listener, Response.ErrorListener errorListener ) {
super ( method, url, errorListener );
this.mListener = listener;
this.mErrorListener = errorListener;
}
@Override
public Map<String, String> getHeaders () throws AuthFailureError {
return super.getHeaders ();
}
@Override
public String getBodyContentType () {
return "multipart/form-data;boundary=" boundary;
}
@Override
public byte[] getBody () throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream ();
DataOutputStream dos = new DataOutputStream ( bos );
try {
// populate text payload
Map<String, String> params = getParams ();
if (params != null && params.size () > 0) {
textParse ( dos, params, getParamsEncoding () );
}
// populate data byte payload
Map<String, DataPart> data = getByteData ();
if (data != null && data.size () > 0) {
dataParse ( dos, data );
}
// close multipart form data after text and file data
dos.writeBytes ( twoHyphens boundary twoHyphens lineEnd );
return bos.toByteArray ();
} catch (IOException e) {
e.printStackTrace ();
}
return null;
}
/**
* Custom method handle data payload.
*
* @return Map data part label with data byte
*/
protected Map<String, DataPart> getByteData () {
return null;
}
@Override
protected Response<NetworkResponse> parseNetworkResponse ( NetworkResponse response ) {
try {
return Response.success ( response, HttpHeaderParser.parseCacheHeaders ( response ) );
} catch (Exception e) {
return Response.error ( new ParseError ( e ) );
}
}
@Override
protected void deliverResponse ( NetworkResponse response ) {
mListener.onResponse ( response );
}
@Override
public void deliverError ( VolleyError error ) {
mErrorListener.onErrorResponse ( error );
}
/**
* Parse string map into data output stream by key and value.
*
* @param dataOutputStream data output stream handle string parsing
* @param params string inputs collection
* @param encoding encode the inputs, default UTF-8
* @throws IOException IOException
*/
private void textParse ( DataOutputStream dataOutputStream, Map<String, String> params, String encoding ) throws IOException {
try {
for (Map.Entry<String, String> entry : params.entrySet ()) {
buildTextPart ( dataOutputStream, entry.getKey (), entry.getValue () );
}
} catch (UnsupportedEncodingException uee) {
throw new RuntimeException ( "Encoding not supported: " encoding, uee );
}
}
/**
* Parse data into data output stream.
*
* @param dataOutputStream data output stream handle file attachment
* @param data loop through data
* @throws IOException IOException
*/
private void dataParse ( DataOutputStream dataOutputStream, Map<String, DataPart> data ) throws IOException {
for (Map.Entry<String, DataPart> entry : data.entrySet ()) {
buildDataPart ( dataOutputStream, entry.getValue (), entry.getKey () );
}
}
/**
* Write string data into header and data output stream.
*
* @param dataOutputStream data output stream handle string parsing
* @param parameterName name of input
* @param parameterValue value of input
* @throws IOException IOException
*/
private void buildTextPart ( DataOutputStream dataOutputStream, String parameterName, String parameterValue ) throws IOException {
dataOutputStream.writeBytes ( twoHyphens boundary lineEnd );
dataOutputStream.writeBytes ( "Content-Disposition: form-data; name=\"" parameterName "\"" lineEnd );
dataOutputStream.writeBytes ( lineEnd );
dataOutputStream.writeBytes ( parameterValue lineEnd );
}
/**
* Write data file into header and data output stream.
*
* @param dataOutputStream data output stream handle data parsing
* @param dataFile data byte as DataPart from collection
* @param inputName name of data input
* @throws IOException IOException
*/
private void buildDataPart ( DataOutputStream dataOutputStream, DataPart dataFile, String inputName ) throws IOException {
dataOutputStream.writeBytes ( twoHyphens boundary lineEnd );
dataOutputStream.writeBytes ( "Content-Disposition: form-data; name=\""
inputName "\"; filename=\"" dataFile.getFileName () "\"" lineEnd );
dataOutputStream.writeBytes ( lineEnd );
ByteArrayInputStream fileInputStream = new ByteArrayInputStream ( dataFile.getContent () );
int bytesAvailable = fileInputStream.available ();
int maxBufferSize = 1024 * 1024;
int bufferSize = Math.min ( bytesAvailable, maxBufferSize );
byte[] buffer = new byte[bufferSize];
int bytesRead = fileInputStream.read ( buffer, 0, bufferSize );
while (bytesRead > 0) {
dataOutputStream.write ( buffer, 0, bufferSize );
bytesAvailable = fileInputStream.available ();
bufferSize = Math.min ( bytesAvailable, maxBufferSize );
bytesRead = fileInputStream.read ( buffer, 0, bufferSize );
}
dataOutputStream.writeBytes ( lineEnd );
}
public static class DataPart {
private final String fileName;
private final byte[] content;
DataPart ( String name, byte[] data ) {
fileName = name;
content = data;
}
String getFileName () {
return fileName;
}
byte[] getContent () {
return content;
}
}
}
After adding the above class, call the below uploadImage
method. Pass the bitmap
which you have received from camera or gallery to this method
/**
* This method sends bitmap image to backend server
*
* @param bitmap
*/
public void uploadImage ( final Bitmap bitmap ) {
VolleyMultipartRequest volleyMultipartRequest = new VolleyMultipartRequest ( Request.Method.POST,
"YOUR_IMAGE_UPLOAD_URL",
this::showSuccessMessage,
this::showErrorMessage
) {
@Override
protected Map<String, DataPart> getByteData () {
Map<String, DataPart> params = new HashMap<> ();
long imageName = System.currentTimeMillis ();
params.put ( "image", new DataPart ( imageName ".jpg", getFileDataFromDrawable ( bitmap ) ) );
return params;
}
//Ignore the below override if you're not using any AUTHORIZATION
@Override
public Map<String, String> getHeaders () {
Map<String, String> params = new HashMap<> ();
params.put ( "authorization", "YOUR AUTH TOKEN" );
return params;
}
};
volleyMultipartRequest.setRetryPolicy ( new DefaultRetryPolicy (
100000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT ) );
Volley.newRequestQueue ( context ).add ( volleyMultipartRequest );
}
/**
* This method is used to display response message
*
* @param response
*/
private void showSuccessMessage ( NetworkResponse response ) {
Log.d ( "LOG", "Response from server: " response.toString () );
}
/**
* This method is used to display error message
*
* @param volleyError
*/
private void showErrorMessage ( VolleyError volleyError ) {
Log.d ( "LOG", "Response from server: " volleyError.getMessage () );
}
/**
* This method converts bitmap to byte array
*
* @param bitmap
* @return byte array
*/
private byte[] getFileDataFromDrawable ( Bitmap bitmap ) {
ByteArrayOutputStream byteArrayOutputStream = null;
try {
byteArrayOutputStream = new ByteArrayOutputStream ();
bitmap.compress ( Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream );
} catch (Exception ignored) {
} finally {
if (byteArrayOutputStream != null) {
try {
byteArrayOutputStream.close ();
} catch (IOException ignore) {
}
}
}
return (byteArrayOutputStream != null ? byteArrayOutputStream.toByteArray () : null);
}
This is the working code which I am using. Hope the above code snippet helps you. Please let me know if I have missed any necessary code snippets in this answer. I will try to update those