Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/223.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 将图像从imageview上载到服务器_Android_File Upload_Retrofit - Fatal编程技术网

Android 将图像从imageview上载到服务器

Android 将图像从imageview上载到服务器,android,file-upload,retrofit,Android,File Upload,Retrofit,我正在尝试从android应用程序向服务器上传图像。我正在调用上载函数并尝试从ImageVeiw获取图像,但没有成功。图像设置在画廊或照相机的图像视图上。 无法获取要发送到服务器的文件 这是我的代码,我用它来设置相机和画廊的图像 if(requestCode == CAMERA_REQUEST & resultCode == RESULT_OK){ Log.d("camera/gallery", "camera"); Bitmap phot

我正在尝试从android应用程序向服务器上传图像。我正在调用上载函数并尝试从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);
        }
我能够获得位图图像并尝试将其保存到文件中。我稍后尝试检索相同的文件,并使用Reformation将其上载到服务器

我从故障时的改装中得到这个错误

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;
        }
    }
public void uploadProfileImage(){
Uri fileUri=getSelectedFile();
if(Uri.EMPTY.equals(fileUri)){
Toast.makeText(此“发生异常”,Toast.LENGTH_SHORT).show();
}否则{
File originalFile=FileUtils.getFile(fileUri.toString());
Log.d(标记“in upload”+originalFile.getAbsolutePath());
RequestBody filePart=RequestBody.create(MediaType.parse(“image/*”),originalFile);
MultipartBody.Part文件=MultipartBody.Part.createFormData(“上载”,originalFile.getName(),filePart);
RequestBody modePart=RequestBody.create(MultipartBody.FORM,“profilepicture”);
APIInterface APIInterface=APIClient.getClient().create(APIInterface.class);
uploadPhoto(文件,modePart).enqueue(新回调(){
@凌驾
公共void onResponse(调用、响应){
Toast.makeText(MainActivity.this,“文件上载”,Toast.LENGTH_SHORT.show();
}
@凌驾
失败时公共无效(调用调用,可丢弃的t){
Toast.makeText(MainActivity.this,“上载失败”,Toast.LENGTH_SHORT.show();
t、 printStackTrace();
}
});
}
}
公共Uri getSelectedFile(){
试一试{
字符串username=“cleaton”;
//从imageview上的图像集获取位图并转换为字节数组
BitmapDrawable BitmapDrawable=(BitmapDrawable)profilePicture.getDrawable();
位图位图=bitmapDrawable.getBitmap();
ByteArrayOutputStream ByteArrayOutputStream=新建ByteArrayOutputStream();
compress(bitmap.CompressFormat.PNG,80,byteArrayOutputStream);
byte[]bitmapdata=byteArrayOutputStream.toByteArray();
byteArrayOutputStream.flush();
byteArrayOutputStream.close();
SimpleDataFormat dateFormat=新的SimpleDataFormat(“yyyyMMdd'T'HHmmss”);
String timeStamp=dateFormat.format(new Date());
File File=新文件(getFilesDir(),用户名+“_profile_“+时间戳+”.png”);
//将字节数组插入名为的文件输出流
FileOutputStream FileOutputStream=openFileOutput(用户名+“\u profile\u”+时间戳+”.png),模式\u PRIVATE);
fileOutputStream.write(位图数据);
fileOutputStream.flush();
fileOutputStream.close();
File profileImageFile=新文件(File.getAbsolutePath());
Log.d(标记“文件检索”+profileImageFile);
urifileuri=Uri.fromFile(profileImageFile);
Log.d(标记,“文件Uri”+fileUri);
返回fileUri;
}捕获(FileNotFoundException fnfe){
fnfe.printStackTrace();
返回null;
}
捕获(ioe异常ioe){
ioe.printStackTrace();
返回null;
}
}

首先需要从Imageview获取位图:

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

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

来解释Webfreak的答案:

BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
一旦检索到
位图
,您就可以创建一个字节流,从中读取字节,并使用类似于下面的方法将其发送到网络套接字。不知道你的上传方法,我不确定这是否足够

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

请将您尝试的代码和设置图像的代码发布到imageview。谢谢。帮了大忙。我已经添加了下一步,其中包含接收到的错误