将图像从imageview上传到服务器

时间:2019-10-17 12:06:21

标签: android file-upload retrofit

我正在尝试将图像从android应用程序上传到服务器。我正在调用上载函数,并尝试从ImageVeiw获取图像,但没有成功。图像是通过图库或相机在ImageVeiw上设置的。 无法将文件发送到服务器

这是我用来设置相机和图库中图像的代码。

if(requestCode == CAMERA_REQUEST & resultCode == RESULT_OK){
            Log.d("camera/gallery", "camera");
            Bitmap photo = (Bitmap) data.getExtras().get("data");
            profilePicture.setImageBitmap(photo);
        } else if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Log.d("camera/gallery", "gallery");

//            get image from gallery
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            Cursor cursor = getActivity().getContentResolver().query(selectedImage,filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();

            Bitmap loadedBitmap = BitmapFactory.decodeFile(picturePath);
//            check orientation of image and rotate if required
            ExifInterface exifInterface = null;
            try{
              File pictureFile = new File(picturePath);
              exifInterface = new ExifInterface(pictureFile.getAbsolutePath());
            } catch (IOException e){
                e.printStackTrace();
            }

            int orientation = exifInterface.ORIENTATION_NORMAL;

            if(exifInterface != null){
                orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            }

            switch(orientation){
                case ExifInterface.ORIENTATION_ROTATE_90:
                    loadedBitmap = rotateBitmap(loadedBitmap, 90);
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    loadedBitmap = rotateBitmap(loadedBitmap, 180);
                    break;

                case ExifInterface.ORIENTATION_ROTATE_270:
                    loadedBitmap = rotateBitmap(loadedBitmap, 270);
                    break;

                case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
                    loadedBitmap = flipBitmap(loadedBitmap, true, false);

                case ExifInterface.ORIENTATION_FLIP_VERTICAL:
                    loadedBitmap = flipBitmap(loadedBitmap, false, true);

                default:
                    loadedBitmap =  loadedBitmap;
            }
//            set image to ImageView
            profilePicture.setImageBitmap(loadedBitmap);
        }

我能够获取位图图像并将其保存到文件中。稍后,我尝试使用改造

检索相同的文件并将其上传到服务器。

我在升级失败时遇到此错误

W/System.err: java.io.FileNotFoundException: file:/data/user/0/com.example.fileuploaddemo/files/cleaton_profile_20191023T111341.png (No such file or directory)

用于存储和检索文件以及发送图像文件的代码

public void uploadProfileImage(){

        Uri fileUri = getSelectedFile();
        if(Uri.EMPTY.equals(fileUri)){
            Toast.makeText(this, "Exception Occurred", Toast.LENGTH_SHORT).show();
        } else {
            File originalFile = FileUtils.getFile(fileUri.toString());
            Log.d(TAG, "in upload"+originalFile.getAbsolutePath());

            RequestBody filePart = RequestBody.create(MediaType.parse("image/*"), originalFile);
            MultipartBody.Part file = MultipartBody.Part.createFormData("upload", originalFile.getName(), filePart);

            RequestBody modePart = RequestBody.create(MultipartBody.FORM, "profilepicture");

            APIInterface apiInterface = APIClient.getClient().create(APIInterface.class);
            apiInterface.uploadPhoto(file, modePart).enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    Toast.makeText(MainActivity.this, "File Uploaded", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    Toast.makeText(MainActivity.this, "Upload Fail", Toast.LENGTH_SHORT).show();
                    t.printStackTrace();
                }
            });
        }

    }

    public Uri getSelectedFile(){
        try{
            String username = "cleaton";

//            get bitmap from image set on  imageview and convert to byte array
            BitmapDrawable bitmapDrawable = (BitmapDrawable) profilePicture.getDrawable();
            Bitmap bitmap = bitmapDrawable.getBitmap();
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 80, byteArrayOutputStream);
            byte[] bitmapdata = byteArrayOutputStream.toByteArray();
            byteArrayOutputStream.flush();
            byteArrayOutputStream.close();

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
            String timeStamp = dateFormat.format(new Date());
            File file = new File(getFilesDir(), username+"_profile_"+timeStamp+".png");

//            insert byte array into file output stream with name
            FileOutputStream fileOutputStream = openFileOutput(username+"_profile_"+timeStamp+".png", MODE_PRIVATE);
            fileOutputStream.write(bitmapdata);
            fileOutputStream.flush();
            fileOutputStream.close();

            File profileImageFile =  new File(file.getAbsolutePath());
            Log.d(TAG, "file retrieve"+profileImageFile);
            Uri fileUri = Uri.fromFile(profileImageFile);
            Log.d(TAG, "file Uri"+fileUri);
            return fileUri;

        } catch(FileNotFoundException fnfe){
            fnfe.printStackTrace();
            return null;
        }
        catch(IOException ioe){
            ioe.printStackTrace();
            return null;
        }
    }

2 个答案:

答案 0 :(得分:0)

首先需要从Imageview获取位图:

BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();

一旦有了位图,就可以将其上传到服务器。

答案 1 :(得分:0)

阐述Webfreak的答案:

BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();

一旦检索到Bitmap,您可以创建一个字节流,您可以使用以下类似的方法从其中读取字节并将其发送到网络套接字。不知道您的上传方法,我不确定是否足够。

 private InputStream getBitmapInputStream(BitmapFactory.Options options,
            Bitmap bitmap) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bitmap.compress(getCompressionFormat(options), 100 /*ignored for PNG*/, bos);
        byte[] bitmapdata = bos.toByteArray();
        return new ByteArrayInputStream(bitmapdata);
    }

    private Bitmap.CompressFormat getCompressionFormat(BitmapFactory.Options options) {
        if (options == null || options.outMimeType == null) return Bitmap.CompressFormat.JPEG;

        if (options.outMimeType.endsWith("/png")) {
            return Bitmap.CompressFormat.PNG;
        } else if (options.outMimeType.endsWith("/webp")) {
            return Bitmap.CompressFormat.WEBP;
        } else {
            return Bitmap.CompressFormat.JPEG;
        }
    }