【问题标题】:How to upload image of desired size as per specification maximum size 50 MB in multi part format to server using retrofit? [duplicate]如何根据规范将所需大小的图像以多部分格式上传到服务器,最大大小为 50 MB? [复制]
【发布时间】:2018-06-09 20:14:27
【问题描述】:

我正在从画廊或相机上传图片,我是 android 新手,所以请帮忙。使用改造将图像作为多部分发送。我需要将图像上传为

高度:4.5 厘米(640 像素) 宽度:3.5 厘米(480 像素)

图片的完整大小不应超过 50 MB。

【问题讨论】:

    标签: android


    【解决方案1】:

    您可以在发送前检查文件大小:

    File file = new File("/sdcard/image.jpg");
    long length = file.length();
    length = length/1024;
    
    if(length < 50000) {
        upload(file);
    } else {
        reduceSize(file);
    }
    
    .
    .
    .
    
    public static boolean reduceSize(File img, long maxSize) {
        boolean result = false;
        BitmapFactory.Options options = new BitmapFactory.Options();
        Bitmap bitmap = null;
        options.inSampleSize = 1;
        while (img.length() > maxSize) {
            img = new File(path);
            options.inSampleSize = options.inSampleSize+1;
            bitmap = BitmapFactory.decodeFile(path, options);
            Utils.deleteRecursive(path);
            result = saveImage(bitmap, path);
        };
        return result;
    }
    
    private void upload(file) {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
    
        // Change base URL to your upload server URL.
        service = new Retrofit.Builder().baseUrl("http://192.168.0.234").client(client).build().create(Service.class);
    
        RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
        MultipartBody.Part body = MultipartBody.Part.createFormData("upload", file.getName(), reqFile);
        RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "upload_test");
    
        retrofit2.Call<okhttp3.ResponseBody> req = service.postImage(body, name);
        req.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { 
                // Do Something
            }
    
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                t.printStackTrace();
            }
        });
    }
    

    【讨论】:

      【解决方案2】:
      class ImageFile(val uri: Uri, name: String) {
      
          val filename: String
      
          init {
              val file = File(Environment.getExternalStorageDirectory().toString() + "/Documents")
              if (!file.exists()) {
                  file.mkdirs()
              }
              val fileNoMedia = File(file.absolutePath + "/.nomedia")
              if (!fileNoMedia.exists())
                  fileNoMedia.createNewFile()
              if (name.toLowerCase().endsWith(".pdf")) {
                  filename = file.absolutePath + "/" + System.currentTimeMillis() + ".pdf"
              } else {
                  filename = file.absolutePath + "/" + System.currentTimeMillis() + ".jpg"
              }
          }
      
          @Throws(IOException::class)
          fun copyFileStream(context: Context, uri: Uri): String {
              if (filename.endsWith(".pdf") || filename.endsWith(".PDF")) {
                  var ins: InputStream? = null
                  var os: OutputStream? = null
                  try {
                      ins = context.getContentResolver().openInputStream(uri)
                      os = FileOutputStream(filename)
                      val buffer = ByteArray(1024)
                      var length: Int = ins.read(buffer)
                      while (length > 0) {
                          os.write(buffer, 0, length);
                          length = ins.read(buffer)
                      }
                  } catch (e: Exception) {
                      e.printStackTrace();
                  } finally {
                      ins?.close()
                      os?.close()
                  }
              } else {
                  var ins: InputStream? = null
                  var os: OutputStream? = null
                  try {
                      ins = context.getContentResolver().openInputStream(uri)
                      var scaledBitmap: Bitmap? = null
                      val options = BitmapFactory.Options()
                      options.inJustDecodeBounds = true
                      var bmp = BitmapFactory.decodeStream(ins, null, options)
                      var actualHeight = options.outHeight
                      var actualWidth = options.outWidth
      
                      //      max Height and width values of the compressed image is taken as 816x612
                      val maxHeight = 816.0f
                      val maxWidth = 612.0f
                      var imgRatio = (actualWidth / actualHeight).toFloat()
                      val maxRatio = maxWidth / maxHeight
      
                      //      width and height values are set maintaining the aspect ratio of the image
                      if (actualHeight > maxHeight || actualWidth > maxWidth) {
                          if (imgRatio < maxRatio) {
                              imgRatio = maxHeight / actualHeight
                              actualWidth = (imgRatio * actualWidth).toInt()
                              actualHeight = maxHeight.toInt()
                          } else if (imgRatio > maxRatio) {
                              imgRatio = maxWidth / actualWidth
                              actualHeight = (imgRatio * actualHeight).toInt()
                              actualWidth = maxWidth.toInt()
                          } else {
                              actualHeight = maxHeight.toInt()
                              actualWidth = maxWidth.toInt()
      
                          }
                      }
      
                      //      setting inSampleSize value allows to load a scaled down version of the original image
                      options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight)
      
                      //      inJustDecodeBounds set to false to load the actual bitmap
                      options.inJustDecodeBounds = false
      
                      //      this options allow android to claim the bitmap memory if it runs low on memory
                      options.inPurgeable = true
                      options.inInputShareable = true
                      options.inTempStorage = ByteArray(16 * 1024)
      
      
                      try {
                          //          load the bitmap from its path
                          ins.close()
                          ins = context.getContentResolver().openInputStream(uri)
                          bmp = BitmapFactory.decodeStream(ins, null, options)
                      } catch (exception: OutOfMemoryError) {
                          exception.printStackTrace()
      
                      }
      
                      try {
                          scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.ARGB_8888)
                      } catch (exception: OutOfMemoryError) {
                          exception.printStackTrace()
                      }
      
                      val ratioX = actualWidth / options.outWidth.toFloat()
                      val ratioY = actualHeight / options.outHeight.toFloat()
                      val middleX = actualWidth / 2.0f
                      val middleY = actualHeight / 2.0f
      
                      val scaleMatrix = Matrix()
                      scaleMatrix.setScale(ratioX, ratioY, middleX, middleY)
      
                      val canvas = Canvas(scaledBitmap!!)
                      canvas.matrix = scaleMatrix
                      canvas.drawBitmap(bmp, middleX - bmp.width / 2, middleY - bmp.height / 2, Paint(Paint.FILTER_BITMAP_FLAG))
      
                      os = FileOutputStream(filename)
                      scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 80, os)
                      val buffer = ByteArray(1024)
                      var length: Int = ins.read(buffer)
                      while (length > 0) {
                          os.write(buffer, 0, length);
                          length = ins.read(buffer)
                      }
                  } catch (e: Exception) {
                      e.printStackTrace();
                  } finally {
                      ins?.close()
                      os?.close()
                  }
              }
              return filename
          }
      
          fun calculateInSampleSize(options: BitmapFactory.Options, reqWidth: Int, reqHeight: Int): Int {
              val height = options.outHeight
              val width = options.outWidth
              var inSampleSize = 1
              if (height > reqHeight || width > reqWidth) {
                  val heightRatio = Math.round(height.toFloat() / reqHeight.toFloat())
                  val widthRatio = Math.round(width.toFloat() / reqWidth.toFloat())
                  inSampleSize = if (heightRatio < widthRatio) heightRatio else widthRatio
              }
              val totalPixels = (width * height).toFloat()
              val totalReqPixelsCap = (reqWidth * reqHeight * 2).toFloat()
              while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
                  inSampleSize++
              }
      
              return inSampleSize
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2014-05-29
        • 2017-08-19
        • 2017-01-10
        • 2016-04-25
        • 1970-01-01
        • 2013-11-25
        • 2014-10-20
        • 2014-03-29
        • 2018-01-26
        相关资源
        最近更新 更多