【问题标题】:How to resize camera or gallery photo如何调整相机或画廊照片的大小
【发布时间】:2019-11-29 22:20:00
【问题描述】:

我从图库或相机中选择一个文件。然后我将它们上传到服务器。但我不能减小它们的大小。图像质量无关紧要。你能告诉我最好的方法吗?我是初学者,我不知道如何使用代码。所以请提供详细信息。

  private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
    );

    // Save a file: path for use with ACTION_VIEW intents
    currentPhotoPath = image.getAbsolutePath();
    return image;
}

 private void dispatchTakePictureIntent() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File

        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(this,
                    "com.example.myapplication.fileprovider",
                    photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
        }
    }
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
        Glide.with(this).load(currentPhotoPath).into(iv);

    } else if (requestCode == SELECT_A_PHOTO && resultCode == RESULT_OK){

        selectedPhoto = data.getData();
        Glide.with(this).load(selectedPhoto).into(iv);

    }

 private void galleryIntent()
{
    Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(i,SELECT_A_PHOTO);
}

My file sizes look like this

【问题讨论】:

    标签: java android image camera gallery


    【解决方案1】:

    我找到了答案。这个方法可以让你缩小尺寸。

    // Get the data from an ImageView as bytes
    imageView.setDrawingCacheEnabled(true);
    imageView.buildDrawingCache();
    Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] data = baos.toByteArray();
    

    New image size

    【讨论】:

      【解决方案2】:

      此函数接受图像路径并转换为位图。 700 是我在这里设置的高度/宽度的基本阈值。您可以相应地更改它并创建缩放位图(数字越小,图像尺寸越小)。 while 循环的每次迭代都将图像缩小到一半。您可以根据需要对其进行修改。

      private Bitmap reduce_image_to_bitmap(String file_path){
          Bitmap bit_map = BitmapFactory.decodeFile(file_path);
          int h = bit_map.getHeight();
          int w = bit_map.getWidth();
          while(h > 700 || w > 700){
              h = h/2;
              w = w/2;
          }
          Bitmap out = Bitmap.createScaledBitmap(bit_map, w, h, false);
          return out;
      }
      

      确保将位图转换为文件,然后继续将文件发送到您的服务器。

      【讨论】:

        【解决方案3】:

        使用这个库:Compressor

        • Compressor 是一个轻量级且功能强大的安卓图像压缩库。 Compressor 将允许您将大照片压缩成更小尺寸的照片,而图像质量的损失非常少或可以忽略不计。

        【讨论】:

          【解决方案4】:

          首先,您需要处理此图像,以便您可以减小尺寸但可以保持质量。您需要运行后台任务,以便在大图像处理期间设备不会发出嘶嘶声。

          然后您可以在此过程中显示一个进度对话框,只需将此代码添加到您的 onCreate 活动中。

            public ProgressDialog progressDialog;
              @Override
              protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
          
              progressDialog = new ProgressDialog(MyProfileEidtActivity.this);
              progressDialog.setMessage("Loading ...");
          
          
              // just execute this process
          
              new ImageProcessing().execute("YOUR IMAGE PATH");
          
            }
          
          
           public class ImageProcessing extends AsyncTask<String, Void, String> {
          
              @Override
              protected void onPreExecute() {
                  super.onPreExecute();
                  progressDialog.setMessage("Image Processing");
                  progressDialog.setCancelable(false);
                  progressDialog.show();
              }
          
              @Override
              protected String doInBackground(String... strings) {
                  Bitmap mainImage = null;
                  Bitmap converetdImage = null;
                  ByteArrayOutputStream bos = null;
                  byte[] bt = null;
                  String encodeString = null;
                  try {
                      mainImage = BitmapFactory.decodeFile(strings[0]);
          
                  /// 500 means image size will be maximum 500 kb
          
                      converetdImage = getResizedBitmap(mainImage, 500);
                      bos = new ByteArrayOutputStream();
                      converetdImage.compress(Bitmap.CompressFormat.JPEG, 50, bos);
                      bt = bos.toByteArray();
                      encodeString = Base64.encodeToString(bt, Base64.DEFAULT);
                  } catch (Exception e) {
                      e.printStackTrace();
                  }
                  return encodeString;
              }
          
              @Override
              protected void onPostExecute(String image) {
                  super.onPostExecute(s);
                  progressDialog.dismiss();
          
               // this image will be your reduced image path
          
              }
          }
          
          public Bitmap getResizedBitmap(Bitmap image, int maxSize) {
              int width = image.getWidth();
              int height = image.getHeight();
          
              float bitmapRatio = (float) width / (float) height;
              if (bitmapRatio > 1) {
                  width = maxSize;
                  height = (int) (width / bitmapRatio);
              } else {
                  height = maxSize;
                  width = (int) (height * bitmapRatio);
              }
              return Bitmap.createScaledBitmap(image, width, height, true);
          }
          

          【讨论】:

            猜你喜欢
            • 2015-02-12
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-04-29
            • 2023-04-05
            • 2011-07-05
            相关资源
            最近更新 更多