how to send the image in an ImageView to a php ser

2019-05-24 10:12发布

问题:

once i have an image in an ImageView, how can i send the image to a web server in the simplest way possible??

I got the image from the gallery using this :

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK)
        try {
            // We need to recyle unused bitmaps
            if (bitmap != null) {
                bitmap.recycle();
            }
            InputStream stream = getContentResolver().openInputStream(
                    data.getData());
            bitmap = BitmapFactory.decodeStream(stream);
            stream.close();
            imageView.setImageBitmap(bitmap);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    super.onActivityResult(requestCode, resultCode, data);
}

and i have set that image to my imageView. I am doing this to show a preview of the image to the uploading person. now how to upload that image to a web server (best n easiest way possible) thankyou

回答1:

i haven't done this with PHP but sent the image with .NET useing base64 string.

convert you image into base64 and send this string on your server. your server will convert this base64 to original image

to convert image into byte[] try following code

private void setPhoto(Bitmap bitmapm) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmapm.compress(Bitmap.CompressFormat.JPEG, 100, baos); 

            byte[] byteArrayImage = baos.toByteArray();
            String imagebase64string = Base64.encodeToString(byteArrayImage,Base64.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


回答2:

This is the code from this URL (I'd pointed in my comment - How do I send a file in Android from a mobile device to server using http?):

String url = "http://yourserver";
File file = new File(Environment.getExternalStorageDirectory(),
        "yourfile");
try {
    HttpClient httpclient = new DefaultHttpClient();

    HttpPost httppost = new HttpPost(url);

    InputStreamEntity reqEntity = new InputStreamEntity(
            new FileInputStream(file), -1);
    reqEntity.setContentType("binary/octet-stream");
    reqEntity.setChunked(true); // Send in multiple parts if needed
    httppost.setEntity(reqEntity);
    HttpResponse response = httpclient.execute(httppost);
    //Do something with response...

} catch (Exception e) {
    // show error
}

Is simple enough I guess. Instead of File and FileInputStream(file) I think You can use Your stream of type InputStream - but I'm not sure...