【问题标题】:uploading image from imageview to server将图像从 imageview 上传到服务器
【发布时间】:2019-10-23 13:55:59
【问题描述】:

我正在尝试将图像从 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;
        }
    }

【问题讨论】:

  • 请将您尝试过的代码和设置图像的代码发布到imageview。

标签: android file-upload retrofit


【解决方案1】:

阐述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;
        }
    }

【讨论】:

  • 谢谢。很大的帮助。我已经添加了正在接收的错误的下一步
【解决方案2】:

你需要从 Imageview 获取位图:

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

一旦你有了位图,你就可以把它上传到服务器。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 2022-09-26
    • 2011-02-02
    • 2015-03-29
    • 2011-10-15
    • 2020-11-19
    相关资源
    最近更新 更多