Java Code Examples for android.graphics.Bitmap#compress()

The following examples show how to use android.graphics.Bitmap#compress() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ImageUtils.java    From Android-utils with Apache License 2.0 6 votes vote down vote up
public static Bitmap compressBySampleSize(final Bitmap src,
                                          final int maxWidth,
                                          final int maxHeight,
                                          final boolean recycle) {
    if (isEmptyBitmap(src)) return null;
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    src.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] bytes = baos.toByteArray();
    BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
    options.inSampleSize = calculateInSampleSize(options, maxWidth, maxHeight);
    options.inJustDecodeBounds = false;
    if (recycle && !src.isRecycled()) src.recycle();
    return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
}
 
Example 2
Source File: ImageEditorModelRenderMediaTransform.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@WorkerThread
@Override
public @NonNull Media transform(@NonNull Context context, @NonNull Media media) {
  ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

  Bitmap bitmap = modelToRender.render(context, size);
  try {
    bitmap.compress(Bitmap.CompressFormat.JPEG, 80, outputStream);

    Uri uri = BlobProvider.getInstance()
                          .forData(outputStream.toByteArray())
                          .withMimeType(MediaUtil.IMAGE_JPEG)
                          .createForSingleSessionOnDisk(context);

    return new Media(uri, MediaUtil.IMAGE_JPEG, media.getDate(), bitmap.getWidth(), bitmap.getHeight(), outputStream.size(), 0, media.getBucketId(), media.getCaption(), Optional.absent());
  } catch (IOException e) {
    Log.w(TAG, "Failed to render image. Using base image.");
    return media;
  } finally {
    bitmap.recycle();
    Util.close(outputStream);
  }
}
 
Example 3
Source File: BaseDiskCache.java    From Android-Universal-Image-Loader-Modify with Apache License 2.0 6 votes vote down vote up
/**
 * 进行保存图片(bitmap)到缓存中 其中根据imageurl来生成缓存文件命名
 * @param imageUri Original image URI
 * @param bitmap   Image bitmap
 * @return
 * @throws IOException
 */
@Override
public boolean save(String imageUri, Bitmap bitmap) throws IOException {
	//根据图片链接地址 生成本地文件
	File imageFile = getFile(imageUri);
	//生成临时文件
	File tmpFile = new File(imageFile.getAbsolutePath() + TEMP_IMAGE_POSTFIX);
	//写入文件
	OutputStream os = new BufferedOutputStream(new FileOutputStream(tmpFile), bufferSize);
	boolean savedSuccessfully = false;
	try {
		//进行图片压缩
		savedSuccessfully = bitmap.compress(compressFormat, compressQuality, os);
	} finally {
		IoUtils.closeSilently(os);
		if (savedSuccessfully && !tmpFile.renameTo(imageFile)) {
			savedSuccessfully = false;
		}
		if (!savedSuccessfully) {
			tmpFile.delete();
		}
	}
	bitmap.recycle();
	return savedSuccessfully;
}
 
Example 4
Source File: MorphingFragment.java    From droid-stealth with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void onClick(View view) {
	ApplicationInfo ai = (ApplicationInfo) view.getTag();

	int iconSize = Utils.px(ICON_SIZE_DP);

	Bitmap bitmap = convertToBitmap(mPackMan.getApplicationIcon(ai), iconSize, iconSize);

	File cache = Utils.getRandomCacheFile(".png");
	try {
		bitmap.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(cache));
	}
	catch (FileNotFoundException e) {
		Utils.toast(R.string.icon_retrieve_failed);
	}

	mCurrentIconPath = Uri.fromFile(cache);
	mCurrentLabel = mPackMan.getApplicationLabel(ai).toString();

	mIcon.setImageBitmap(bitmap);
	mName.setText(mCurrentLabel);
	Utils.fadein(mIcon, 75);
	Utils.fadein(mName, 100);
	mAppDialog.dismiss();
}
 
Example 5
Source File: FileUtil.java    From CameraView with Apache License 2.0 6 votes vote down vote up
public static String saveBitmap(String dir, Bitmap b) {
    DST_FOLDER_NAME = dir;
    String path = initPath();
    long dataTake = System.currentTimeMillis();
    String jpegName = path + File.separator + "picture_" + dataTake + ".jpg";
    try {
        FileOutputStream fout = new FileOutputStream(jpegName);
        BufferedOutputStream bos = new BufferedOutputStream(fout);
        b.compress(Bitmap.CompressFormat.JPEG, 100, bos);
        bos.flush();
        bos.close();
        return jpegName;
    } catch (IOException e) {
        e.printStackTrace();
        return "";
    }
}
 
Example 6
Source File: CompressUtils.java    From zone-sdk with MIT License 6 votes vote down vote up
/**
 *
 * @param bt	 想要压缩位图
 * @param targetSize  目标Kb
 * @param qualityMin  最低质量
 * @return  压缩后的位图
 */
public static Bitmap compressBitmap(Bitmap bt,int targetSize,int qualityMin) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bt.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
    LogZSDK.INSTANCE.d("压缩的时候_开始_大小:" + baos.toByteArray().length / 1024 * 4 + "kb");
    int options = 100;
    int step = 10;
    while (baos.toByteArray().length / 1024 * 4 > targetSize) {
        // 循环判断如果压缩后图片是否大于300kb 左右,大于继续压缩 经过我的实践貌似的*4
        baos.reset();// 重置baos即清空baos
        bt.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%,把压缩后的数据存放到baos中
        if (options < qualityMin) {
            break;
        }
        if (options > step) {
            options -= step;// 每次都减少10
        }
        else {
            break;
        }
    }
    LogZSDK.INSTANCE.d("压缩的时候_完成后_大小:" + baos.toByteArray().length / 1024 * 4 + "kb");
    ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
    Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
    return bitmap;
}
 
Example 7
Source File: DecryptableStreamLocalUriFetcher.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected InputStream loadResource(Uri uri, ContentResolver contentResolver) throws FileNotFoundException {
  if (MediaUtil.hasVideoThumbnail(uri)) {
    Bitmap thumbnail = MediaUtil.getVideoThumbnail(context, uri, 1000);

    if (thumbnail != null) {
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, baos);
      ByteArrayInputStream thumbnailStream = new ByteArrayInputStream(baos.toByteArray());
      thumbnail.recycle();
      return thumbnailStream;
    }
  }

  try {
    return PartAuthority.getAttachmentThumbnailStream(context, uri);
  } catch (IOException ioe) {
    Log.w(TAG, ioe);
    throw new FileNotFoundException("PartAuthority couldn't load Uri resource.");
  }
}
 
Example 8
Source File: FileUtil.java    From imsdk-android with MIT License 6 votes vote down vote up
public static String saveBitmap(String dir, Bitmap b) {
    DST_FOLDER_NAME = dir;
    String path = initPath();
    long dataTake = System.currentTimeMillis();
    String jpegName = path + File.separator + "picture_" + dataTake + ".jpg";
    try {
        FileOutputStream fout = new FileOutputStream(jpegName);
        BufferedOutputStream bos = new BufferedOutputStream(fout);
        b.compress(Bitmap.CompressFormat.JPEG, 100, bos);
        bos.flush();
        bos.close();
        return jpegName;
    } catch (IOException e) {
        e.printStackTrace();
        return "";
    }
}
 
Example 9
Source File: LoadImageUtil.java    From natrium-android-wallet with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void saveImage(Context context, Bitmap b, String imageName) {
    FileOutputStream foStream;
    try {
        foStream = context.openFileOutput(imageName, Context.MODE_PRIVATE);
        b.compress(Bitmap.CompressFormat.PNG, 100, foStream);
        foStream.close();
    } catch (Exception e) {
        Timber.e("Failed to save image to disk: %s", imageName);
        e.printStackTrace();
    }
}
 
Example 10
Source File: BaseImageDownloader.java    From Roid-Library with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves {@link InputStream} of image by URI (image is located in
 * drawable resources of application).
 * 
 * @param imageUri Image URI
 * @param extra Auxiliary object which was passed to
 *            {@link DisplayImageOptions.Builder#extraForDownloader(Object)
 *            DisplayImageOptions.extraForDownloader(Object)}; can be null
 * @return {@link InputStream} of image
 */
protected InputStream getStreamFromDrawable(String imageUri, Object extra) {
    String drawableIdString = Scheme.DRAWABLE.crop(imageUri);
    int drawableId = Integer.parseInt(drawableIdString);
    BitmapDrawable drawable = (BitmapDrawable) context.getResources().getDrawable(drawableId);
    Bitmap bitmap = drawable.getBitmap();

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    bitmap.compress(CompressFormat.PNG, 0, os);
    return new ByteArrayInputStream(os.toByteArray());
}
 
Example 11
Source File: DiskLruImageCache.java    From Android-ImageManager with MIT License 5 votes vote down vote up
private boolean writeBitmapToFile(final Bitmap bitmap, final DiskLruCache.Editor editor) throws IOException {
    OutputStream out = null;
    try {
        out = new BufferedOutputStream(editor.newOutputStream(0), Utils.IO_BUFFER_SIZE);
        return bitmap.compress(compressFormat, compressQuality, out);
    } finally {
        if (out != null) {
            out.close();
        }
    }
}
 
Example 12
Source File: CropImageActivity.java    From memoir with Apache License 2.0 5 votes vote down vote up
private void saveOutput(Bitmap croppedImage) {
    if (mSaveUri != null) {
        OutputStream out = null;
        try {
            out = getContentResolver().openOutputStream(mSaveUri);
            if (out != null) {
                croppedImage.compress(mOutputFormat, 90, out);
            }
        } catch (IOException ex) {
            Log.e(getClass().getSimpleName(), "Cannot open file: " + mSaveUri, ex);
            setResult(RESULT_CANCELED);
            finish();
            return;
        } finally {
            Helper.closeQuietly(out);
        }

        Bundle extras = new Bundle();
        Intent intent = new Intent(mSaveUri.toString());
        intent.putExtras(extras);
        intent.putExtra(IMAGE_SOURCE_FILE, mImageSource);
        intent.putExtra(IMAGE_DESTINATION_FILE, mImageDest);
        intent.putExtra(ORIENTATION_IN_DEGREES,
                getOrientationInDegree(this));
        setResult(RESULT_OK, intent);

    } else {
        Log.e(getClass().getSimpleName(), "not defined image url");
    }
    croppedImage.recycle();
    finish();
}
 
Example 13
Source File: CropImageActivity.java    From UltimateAndroid with Apache License 2.0 5 votes vote down vote up
private void saveOutput(Bitmap croppedImage) {
    if (saveUri != null) {
        OutputStream outputStream = null;
        try {
            outputStream = getContentResolver().openOutputStream(saveUri);
            if (outputStream != null) {
                croppedImage.compress(Bitmap.CompressFormat.JPEG, 90, outputStream);
            }
        } catch (IOException e) {
            setResultException(e);
            Logs.e("Cannot open file: " + saveUri, e);
        } finally {
            CropUtil.closeSilently(outputStream);
        }

        if (!IN_MEMORY_CROP) {
            // In-memory crop negates the rotation
            CropUtil.copyExifRotation(
                    CropUtil.getFromMediaUri(getContentResolver(), sourceUri),
                    CropUtil.getFromMediaUri(getContentResolver(), saveUri)
            );
        }

        setResultUri(saveUri);
    }

    final Bitmap b = croppedImage;
    handler.post(new Runnable() {
        public void run() {
            imageView.clear();
            b.recycle();
        }
    });

    finish();
}
 
Example 14
Source File: CameraViewHolder.java    From haven with GNU General Public License v3.0 5 votes vote down vote up
private void saveDetectedImage (Bitmap rawBitmap)
{
    if (serviceMessenger != null) {
        Message message = new Message();
        message.what = EventTrigger.CAMERA;

        try {

            File fileImageDir = new File(this.context.getExternalFilesDir(null), prefs.getDefaultMediaStoragePath());
            fileImageDir.mkdirs();

            String ts = new SimpleDateFormat(Utils.DATE_TIME_PATTERN,
                    Locale.getDefault()).format(new Date());

            File fileImage = new File(fileImageDir, ts.concat(".detected.original.jpg"));
            FileOutputStream stream = new FileOutputStream(fileImage);
            rawBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);

            stream.flush();
            stream.close();
            message.getData().putString(MonitorService.KEY_PATH, fileImage.getAbsolutePath());

            //store the still match frame, even if doing video
            serviceMessenger.send(message);

            if (prefs.getVideoMonitoringActive() && (!doingVideoProcessing)) {
                recordVideo();

            }

        } catch (Exception e) {
            // Cannot happen
            Log.e("CameraViewHolder", "error creating image", e);
        }
    }
}
 
Example 15
Source File: SpecialIconStore.java    From LaunchTime with GNU General Public License v3.0 5 votes vote down vote up
public static void saveBitmap(Context context, ComponentName cname, Bitmap bitmap, IconType iconType) {

        try  {
            String fname = makeSafeName(cname, iconType);
            FileOutputStream fos = context.openFileOutput(fname, Context.MODE_PRIVATE);
            bitmap.compress(Bitmap.CompressFormat.PNG,100,fos);
            fos.close();
            Log.d("SpecialIconStore", "Saved icon " + fname);
        } catch (IOException e) {
            Log.e("SpecialIconStore", e.getMessage(), e);
        }
    }
 
Example 16
Source File: DeviceAppsPlugin.java    From flutter_plugin_device_apps with Apache License 2.0 4 votes vote down vote up
private String encodeToBase64(Bitmap image, Bitmap.CompressFormat compressFormat, int quality) {
    ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
    image.compress(compressFormat, quality, byteArrayOS);
    return Base64.encodeToString(byteArrayOS.toByteArray(), Base64.NO_WRAP);
}
 
Example 17
Source File: TransactionViewActivity.java    From budget-watch with GNU General Public License v3.0 4 votes vote down vote up
private boolean reencodeImageWithQuality(String original, int quality)
{
    File destFile = new File(original);
    File tmpLocation = getNewImageLocation();

    try
    {
        if (tmpLocation == null)
        {
            throw new IOException("Could not create location for tmp file");
        }

        boolean created = tmpLocation.createNewFile();
        if (created == false)
        {
            throw new IOException("Could not create tmp file");
        }

        Bitmap bitmap = BitmapFactory.decodeFile(original);
        FileOutputStream fOut = new FileOutputStream(tmpLocation);
        boolean fileWritten = bitmap.compress(Bitmap.CompressFormat.JPEG, quality, fOut);
        fOut.flush();
        fOut.close();

        if (fileWritten == false)
        {
            throw new IOException("Could not down compress file");
        }

        boolean renamed = tmpLocation.renameTo(destFile);
        if (renamed == false)
        {
            throw new IOException("Could not move converted file");
        }

        Log.i(TAG, "Image file " + original + " saved at quality " + quality);

        return true;
    }
    catch(IOException e)
    {
        Log.e(TAG, "Failed to encode image", e);

        for(File item : new File[]{tmpLocation, destFile})
        {
            if(item != null)
            {
                boolean result = item.delete();
                if(result == false)
                {
                    Log.w(TAG, "Failed to delete image file: " + item.getAbsolutePath());
                }
            }
        }
    }

    return false;
}
 
Example 18
Source File: loveviayou.java    From stynico with MIT License 4 votes vote down vote up
public static void a(Context con,Uri in)
{

	Uri uri = in;
	ContentResolver cr = con.getContentResolver();  
	try
	{
		Bitmap bmp = BitmapFactory.decodeStream(cr.openInputStream(uri));
		//Bitmap bmp = getUrlBitmap(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Tencent/A.mp4");

		File[] files = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/DCIM/Camera/").listFiles();
		if (files == null)
		{
			Toast.makeText(con, "没安装网易音乐或者是没有加载广告", Toast.LENGTH_LONG).show();
			return;
		}
		Vector<String> c=new Vector<String>();
		for (File f : files) 
		{
			if (f.isDirectory())
			{
				File[] temp_files=f.listFiles();
				if (temp_files == null) continue;
				for (File inner_f : temp_files)
				{

					if (inner_f.isFile())
						c.add(inner_f.getAbsolutePath());
				}
			}
			if (f.isFile())
				c.add(f.getAbsolutePath());
		}
		for (String s : c)
		{
			OutputStream ops=new FileOutputStream(s);
			bmp.compress(Bitmap.CompressFormat.JPEG, 100, ops);
		}


	}
	catch (FileNotFoundException e)
	{
		e.printStackTrace();
	}  
	Toast.makeText(con, "替换完成", Toast.LENGTH_SHORT).show();
	//finish();

}
 
Example 19
Source File: ImageConvertor.java    From Android with Apache License 2.0 4 votes vote down vote up
public static byte[] bitmapToPng(Bitmap bitmap) {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    bitmap.compress(CompressFormat.PNG, 100, out);
    return out.toByteArray();
}
 
Example 20
Source File: ExifInterface.java    From TurboLauncher with Apache License 2.0 3 votes vote down vote up
/**
 * Writes the tags from this ExifInterface object into a jpeg compressed
 * bitmap, removing prior exif tags.
 *
 * @param bmap a bitmap to compress and write exif into.
 * @param exifOutStream the OutputStream to which the jpeg image with added
 *            exif tags will be written.
 * @throws IOException
 */
public void writeExif(Bitmap bmap, OutputStream exifOutStream) throws IOException {
    if (bmap == null || exifOutStream == null) {
        throw new IllegalArgumentException(NULL_ARGUMENT_STRING);
    }
    OutputStream s = getExifWriterStream(exifOutStream);
    bmap.compress(Bitmap.CompressFormat.JPEG, 90, s);
    s.flush();
}