图片压缩到指定尺寸和大小

第一步:

/**
       * 对上次的图片进行压缩,压缩在100kb以内
       *
       * @param image
       * @return
       */
       private Bitmap compressImage(Bitmap image) {

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            image.compress(Bitmap.CompressFormat. JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到 baos中
             int options = 100;
             while ( baos.toByteArray().length / 1024>100) {  //循环判断如果压缩后图片是否大于100kb,大于继续压缩
                  baos.reset(); //重置baos即清空baos
                  image.compress(Bitmap.CompressFormat. JPEG, options, baos);//这里压缩options%,把压缩后的数据存放到 baos中
                  options -= 10; //每次都减少10
            }
            ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据 baos存放到ByteArrayInputStream中
            Bitmap bitmap = BitmapFactory. decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
             return bitmap;
      }

/**
       * 缩放图片到指定尺寸
       * @param image
       * @return
       */
       private Bitmap comp(Bitmap image) {

          ByteArrayOutputStream baos = new ByteArrayOutputStream();
          image.compress(Bitmap.CompressFormat. JPEG, 100, baos);
          if( baos.toByteArray().length / 1024>512) {//判断如果图片大于1M,进行压缩避免在生成图片(BitmapFactory.decodeStream)时溢出
              baos.reset(); //重置baos即清空baos
              image.compress(Bitmap.CompressFormat. JPEG, 50, baos);//这里压缩50%,把压缩后的数据存放到 baos中
          }
          ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
          BitmapFactory.Options newOpts = new BitmapFactory.Options();
          //开始读入图片,此时把options.inJustDecodeBounds 设回true了
          newOpts. inJustDecodeBounds = true ;
          Bitmap bitmap = BitmapFactory. decodeStream(isBm, null, newOpts);
          newOpts. inJustDecodeBounds = false ;
          int w = newOpts.outWidth ;
          int h = newOpts.outHeight ;
          //现在主流手机比较多是800*480分辨率,所以高和宽我们设置为
          float hh = 800f;//这里设置高度为800f
          float ww = 480f;//这里设置宽度为480f
          //缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
          int be = 1;//be=1表示不缩放
          if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
              be = ( int) (newOpts.outWidth / ww);
          } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
              be = ( int) (newOpts.outHeight / hh);
          }
          if (be <= 0)
              be = 1;
          newOpts. inSampleSize = be;//设置缩放比例
          //重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了
          isBm = new ByteArrayInputStream(baos.toByteArray());
          bitmap = BitmapFactory. decodeStream(isBm, null, newOpts);
          return compressImage(bitmap);//压缩好比例大小后再进行质量压缩
      }


第二步:
 Bitmap   bitmap=comp(bitmap );//为压缩后的图片

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以使用 JavaScript 库或框架来实现图片压缩功能。 例如可以使用 "canvas" 元素和 "FileReader" 对象来实现图片压缩。 以下是一个简单的示例代码: ``` // 选择文件 input 元素的 id const inputId = 'input'; // 压缩后图片的大小(单位为字节) const targetSize = 100000; // 选择文件 const input = document.getElementById(inputId); const file = input.files[0]; // 创建 FileReader 对象 const reader = new FileReader(); // 当文件加载完成时运行的函数 reader.onload = function(event) { // 获取加载的图片 const img = new Image(); img.src = event.target.result; // 当图片加载完成时运行的函数 img.onload = function() { // 获取图片的原始大小 const originalSize = file.size; // 计算图片压缩比例 const ratio = targetSize / originalSize; // 创建 canvas 元素 const canvas = document.createElement('canvas'); // 设置 canvas 的宽度和高度 canvas.width = img.width; canvas.height = img.height; // 将图片绘制到 canvas 上 const ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0); // 压缩图片 const compressedDataUrl = canvas.toDataURL('image/jpeg', ratio); // 使用压缩后的图片数据 // ... }; }; // 以 DataURL 的形式读取文件 reader.readAsDataURL(file); ``` 这段代码会读取选择的文件,将其加载到内存中,然后将其绘制到 canvas 上,并使用指定的压缩比例进行压缩。 ### 回答2: 使用js将图片压缩指定大小可以通过以下步骤实现: 1. 首先,通过HTML的<input>元素让用户选择需要压缩的图片文件。可以使用<input type="file">来创建一个文件上传按钮,并添加一个id以便后续操作。 2. 使用FileReader对象读取用户选择的图片文件,并将其转换成Data URL的形式,以便后续操作。可以通过以下代码实现: ``` const fileInput = document.getElementById("fileInput"); const reader = new FileReader(); fileInput.addEventListener("change", function(event) { const file = event.target.files[0]; reader.onload = function(e) { const dataUrl = e.target.result; // 后续操作 } reader.readAsDataURL(file); }); ``` 3. 接下来,可以使用HTML5的Canvas元素来进行图片的压缩操作。创建一个Canvas元素,并通过设置其宽度和高度来指定压缩后的尺寸。 4. 使用Canvas的context对象,调用drawImage()方法将读取到的图片绘制到Canvas上。可以通过以下代码实现: ``` const canvas = document.createElement("canvas"); const ctx = canvas.getContext("2d"); const image = new Image(); image.src = dataUrl; image.onload = function() { // 计算压缩后的尺寸 const maxWidth = 500; const maxHeight = 500; let width = image.width; let height = image.height; if (width > height) { if (width > maxWidth) { height *= maxWidth / width; width = maxWidth; } } else { if (height > maxHeight) { width *= maxHeight / height; height = maxHeight; } } // 设置Canvas尺寸 canvas.width = width; canvas.height = height; // 在Canvas上绘制压缩后的图片 ctx.drawImage(image, 0, 0, width, height); // 获取压缩后的图片数据URL const compressedDataUrl = canvas.toDataURL("image/jpeg", 0.8); // 压缩后的图片处理操作 // ... } ``` 5. 最后,可以将压缩后的图片数据URL用于展示或上传等操作。可以通过设置img元素的src属性来显示压缩后的图片,或通过Ajax等方式将数据URL发送到服务器端。 通过以上步骤,可以使用js将图片压缩指定大小。 ### 回答3: 使用 JavaScript 将图片压缩指定大小可以通过以下步骤实现: 1. 创建一个 <input> 元素,允许用户选择要上传的图片文件。 2. 监听 <input> 元素的 `change` 事件,当用户选择图片后触发。 3. 在 `change` 事件处理程序中,使用 `FileReader` 对象读取用户选择的图片文件。 4. 在 `FileReader` 的 `onload` 事件中,获取读取的图片数据,并创建一个新的 <img> 元素来展示图片。 5. 获取目标图片的原始宽度和高度。 6. 创建一个 <canvas> 元素,设置宽度和高度为指定的压缩大小。 7. 在 <canvas> 上绘制图片,并指定压缩后的宽度和高度。 8. 使用 `canvas.toDataURL()` 方法将压缩后的图片转换为 base64 编码的字符串。 9. 将该字符串赋值给 <img> 元素的 `src` 属性,显示压缩后的图片。 下面是一个简单的示例代码: ```javascript function compressImage(file, maxWidth, maxHeight) { const reader = new FileReader(); reader.onload = function(event) { const img = new Image(); img.src = event.target.result; img.onload = function() { const canvas = document.createElement('canvas'); let width = img.width; let height = img.height; if (width > maxWidth) { height = Math.round(height * maxWidth / width); width = maxWidth; } if (height > maxHeight) { width = Math.round(width * maxHeight / height); height = maxHeight; } canvas.width = width; canvas.height = height; const ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0, width, height); const compressedDataUrl = canvas.toDataURL('image/jpeg', 0.7); const compressedImage = document.createElement('img'); compressedImage.src = compressedDataUrl; document.body.appendChild(compressedImage); }; }; reader.readAsDataURL(file); } const fileInput = document.getElementById('fileInput'); fileInput.addEventListener('change', function(event) { const file = event.target.files[0]; compressImage(file, 800, 600); // 指定压缩大小为 800x600 }); ``` 这个示例代码通过监听文件选择事件,将选择的图片压缩后显示在页面上。使用 `<input>` 元素选择文件,并通过调用 `compressImage` 函数传入目标图片文件、最大宽度和最大高度即可实现将图片压缩指定大小

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值