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

The following are Jave code examples for showing how to use compress() of the android.graphics.Bitmap class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: Camera-Roll-Android-App   File: RAWImageBitmapRegionDecoder.java   View Source Code Vote up 7 votes
@Override
public Point init(Context context, Uri uri) throws Exception {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = 1;
    options.inJustDecodeBounds = false;

    ContentResolver resolver = context.getContentResolver();
    InputStream inputStream = resolver.openInputStream(uri);
    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

    String filename = String.valueOf(uri.toString().hashCode());
    cacheFile = new File(context.getCacheDir(), filename);
    FileOutputStream fileOutputStream = new FileOutputStream(cacheFile);
    bitmap.compress(Bitmap.CompressFormat.JPEG, JPEG_QUALITY, fileOutputStream);

    decoder = new CustomRegionDecoder();
    return decoder.init(context, Uri.fromFile(cacheFile));
}
 
Example 2
Project: DailyStudy   File: FileUtils.java   View Source Code Vote up 6 votes
/**
 * 将图片写入sd卡
 *
 */
public static  void inputPicTosdcard(Bitmap bitmap, String picName) {
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);

        File SDFile = Environment.getExternalStorageDirectory();
        File destDir = new File(SDFile.getAbsolutePath() + "/qqcyData/");//文件目录

        if (!destDir.exists()) {//判断目录是否存在,不存在创建
            destDir.mkdir();//创建目录
        }
        File pic = new File(destDir.getPath() + File.separator +picName);
        if (!pic.exists()) {
            try {
                pic.createNewFile();//创建文件
                FileOutputStream outputStream = new FileOutputStream(pic, true);
                outputStream.write(baos.toByteArray());//写入内容
                outputStream.close();//关闭流
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
 
Example 3
Project: ImageLoaderSupportGif   File: BaseImageDownloader.java   View Source Code Vote up 6 votes
/**
 * Retrieves {@link InputStream} of image by URI (image is accessed using {@link ContentResolver}).
 *
 * @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
 * @throws FileNotFoundException if the provided URI could not be opened
 */
protected InputStream getStreamFromContent(String imageUri, Object extra) throws FileNotFoundException {
	ContentResolver res = context.getContentResolver();

	Uri uri = Uri.parse(imageUri);
	if (isVideoContentUri(uri)) { // video thumbnail
		Long origId = Long.valueOf(uri.getLastPathSegment());
		Bitmap bitmap = MediaStore.Video.Thumbnails
				.getThumbnail(res, origId, MediaStore.Images.Thumbnails.MINI_KIND, null);
		if (bitmap != null) {
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			bitmap.compress(CompressFormat.PNG, 0, bos);
			return new ByteArrayInputStream(bos.toByteArray());
		}
	} else if (imageUri.startsWith(CONTENT_CONTACTS_URI_PREFIX)) { // contacts photo
		return getContactPhotoStream(uri);
	}

	return res.openInputStream(uri);
}
 
Example 4
Project: andcouchbaseentity   File: TaskActivity.java   View Source Code Vote up 6 votes
private void attachImage(TaskEntity task, Bitmap image) {
    if (task == null || image == null) return;



    ByteArrayOutputStream out = new ByteArrayOutputStream();
    image.compress(Bitmap.CompressFormat.JPEG, 50, out);
    ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
    task.setImage(in);

    try {
        task.save();
    } catch (CouchbaseLiteException e) {
        Log.e(Application.TAG, "Cannot attach image", e);
    }
}
 
Example 5
Project: letv   File: BaseDiscCache.java   View Source Code Vote up 6 votes
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), this.bufferSize);
    boolean savedSuccessfully = false;
    try {
        savedSuccessfully = bitmap.compress(this.compressFormat, this.compressQuality, os);
        bitmap.recycle();
        return savedSuccessfully;
    } finally {
        IoUtils.closeSilently(os);
        if (savedSuccessfully && !tmpFile.renameTo(imageFile)) {
            savedSuccessfully = false;
        }
        if (!savedSuccessfully) {
            tmpFile.delete();
        }
    }
}
 
Example 6
Project: RLibrary   File: RUtils.java   View Source Code Vote up 6 votes
/**
 * 简单的压缩图片
 * 图片对象有可能会很大, 但是转成成 bytes之后, 会很小, 此方法会判断不准确
 */
@Deprecated
public static Bitmap compressBitmap(Bitmap image) {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
    int options = 90;

    while (baos.toByteArray().length / 1024 > 200) { // 循环判断如果压缩后图片是否大于200kb,大于继续压缩
        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;
}
 
Example 7
Project: haven   File: ImageCodec.java   View Source Code Vote up 6 votes
/**
    * Rotates a bitmat of the given degrees
    * @param bmp
    * @param degrees
    * @return
    */
   public static Bitmap rotate(Bitmap bmp, int degrees, boolean reflex) {
       if (bmp==null) throw new NullPointerException();
       
	//getting scales of the image  
	int width = bmp.getWidth();  
	int height = bmp.getHeight();  
	
	//Creating a Matrix and rotating it to specified degrees   
	Matrix matrix = new Matrix();
	matrix.postRotate(degrees);
	if (reflex)   matrix.postScale(-1, 1);
	
	//Getting the rotated Bitmap  
	Bitmap rotatedBmp = Bitmap.createBitmap(bmp, 0, 0, width, height, matrix, true);
	ByteArrayOutputStream stream = new ByteArrayOutputStream();
	rotatedBmp.compress(Bitmap.CompressFormat.JPEG, 100, stream); 
	return rotatedBmp;
}
 
Example 8
Project: magic_imageloader_network   File: BaseDownloadStream.java   View Source Code Vote up 5 votes
private InputStream getStreamFromVideo(ImageDownloadInfo imageDownloadInfo) throws IOException {
    try {
        if (imageDownloadInfo.getExtraInfo() < MediaStore.Images.Thumbnails.MINI_KIND || imageDownloadInfo.getExtraInfo() > MediaStore.Video.Thumbnails.MICRO_KIND) {
            imageDownloadInfo.setExtraInfo(MediaStore.Images.Thumbnails.MINI_KIND);
        }
        Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(imageDownloadInfo.getImageUrl(), imageDownloadInfo.getExtraInfo());
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 0, os);
        return new ByteArrayInputStream(os.toByteArray());
    } catch (Exception e) {
        Log.e("error", "e: " + e.toString());
    }
    return null;
}
 
Example 9
Project: stynico   File: FileUtil.java   View Source Code Vote up 5 votes
/**
 * 获取压缩后图片的二进制数据
 * @param srcPath
 * @return
 */
public  byte[] getCompressedImage(String srcPath) {
    if (!new File(srcPath).exists()){
        return null;
    }

    BitmapFactory.Options newOpts = new BitmapFactory.Options();
    //开始读入图片,此时把options.inJustDecodeBounds 设回true了
    newOpts.inJustDecodeBounds = true;
    Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);//此时返回bm为空

    newOpts.inJustDecodeBounds = false;
    int w = newOpts.outWidth;
    int h = newOpts.outHeight;
    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了
    bitmap = BitmapFactory.decodeFile(srcPath, newOpts);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
    int options = 100;
    while (baos.toByteArray().length / 1024 > 300) {    //循环判断如果压缩后图片是否大于300kb,大于继续压缩
        baos.reset();//重置baos即清空baos
        options -= 15;//每次都减少15
        bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%,把压缩后的数据存放到baos中
    }
    return baos.toByteArray();
}
 
Example 10
Project: anyRTC-RTCP-Android   File: DecodeHandler.java   View Source Code Vote up 5 votes
static void bundleThumbnail(PlanarYUVLuminanceSource source, Bundle bundle) {
	int[] pixels = source.renderThumbnail();
	int width = source.getThumbnailWidth();
	int height = source.getThumbnailHeight();
	Bitmap bitmap = Bitmap.createBitmap(pixels, 0, width, width, height, Bitmap.Config.ARGB_8888);
	ByteArrayOutputStream out = new ByteArrayOutputStream();
	bitmap.compress(Bitmap.CompressFormat.JPEG, 50, out);
	bundle.putByteArray(DecodeThread.BARCODE_BITMAP, out.toByteArray());
}
 
Example 11
Project: 2017NASA_NCTUBeach   File: InfoActivity.java   View Source Code Vote up 5 votes
private void takeScreenshot() {
    Date now = new Date();
    android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        return;
    }

    try {
        // image naming and path  to include sd card  appending name you choose for file
        String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";

        // create bitmap screen capture
        View v1 = getWindow().getDecorView().getRootView();
        v1.setDrawingCacheEnabled(true);
        Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
        v1.setDrawingCacheEnabled(false);

        File imageFile = new File(mPath);

        FileOutputStream outputStream = new FileOutputStream(imageFile);
        int quality = 100;
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
        outputStream.flush();
        outputStream.close();

        openScreenshot(imageFile);
    } catch (Throwable e) {
        // Several error may come out with file handling or OOM
        e.printStackTrace();
    }
}
 
Example 12
Project: yyox   File: PictureUtil.java   View Source Code Vote up 5 votes
public static void saveTempPicture(String filePath,String fileTempPath){
    File file = new File(fileTempPath);
    Bitmap bmp = PictureUtil.getSmallBitmap(filePath,120,120);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    // 把压缩后的数据存放到baos中
    bmp.compress(Bitmap.CompressFormat.PNG, 10, baos);
    try {
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(baos.toByteArray());
        fos.flush();
        fos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 13
Project: browser   File: LightningView.java   View Source Code Vote up 5 votes
private void cacheFavicon(Bitmap icon) {
	String hash = String.valueOf(Utils.getDomainName(getUrl()).hashCode());
	Log.d(Constants.TAG, "Caching icon for " + Utils.getDomainName(getUrl()));
	File image = new File(mActivity.getCacheDir(), hash + ".png");
	try {
		FileOutputStream fos = new FileOutputStream(image);
		icon.compress(Bitmap.CompressFormat.PNG, 100, fos);
		fos.flush();
		fos.close();
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 14
Project: MetadataEditor   File: StandardArtwork.java   View Source Code Vote up 5 votes
@Override
public void setImageFromBitmap(Bitmap bitmap) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
    byte[] imageData = stream.toByteArray();
    setBinaryData(imageData);
    setMimeType(ImageFormats.getMimeTypeForBinarySignature(imageData));
    setDescription("");
    setPictureType(PictureTypes.DEFAULT_ID);
}
 
Example 15
Project: decoy   File: ACache.java   View Source Code Vote up 5 votes
private static byte[] Bitmap2Bytes(Bitmap bm) {
	if (bm == null) {
		return null;
	}
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
	return baos.toByteArray();
}
 
Example 16
Project: Loyalty   File: CacheManager.java   View Source Code Vote up 4 votes
public void addToCache(Bitmap bitmap, Card card, Cache cache) throws FileNotFoundException {
    String fileName = cache.getCacheLocation(getFileName(card));
    FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
    bitmap.compress(Constants.IMAGE_COMPRESS_FORMAT, Constants.IMAGE_QUALITY, fos);
}
 
Example 17
Project: Show_Chat   File: ImageUtils.java   View Source Code Vote up 4 votes
public static String encodeBase64(Bitmap imgBitmap){
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    imgBitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
    byte[] byteArray = byteArrayOutputStream.toByteArray();
    return Base64.encodeToString(byteArray, Base64.DEFAULT);
}
 
Example 18
Project: stynico   File: loveviayou.java   View Source Code Vote up 4 votes
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
Project: AmenEye   File: ImageFactory.java   View Source Code Vote up 3 votes
/**
 * Store bitmap into specified image path
 *
 * @param bitmap
 * @param outPath
 * @throws FileNotFoundException
 */
public void storeImage(Bitmap bitmap, String outPath) throws FileNotFoundException {
    FileOutputStream os = new FileOutputStream(outPath);
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
}
 
Example 20
Project: MoodSwings   File: MoodEvent.java   View Source Code Vote up 3 votes
/**
 *
 * @param bitmap
 * @return a String value for the Bitmap photo.
 *
 * This is to aid in persistence.
 *
 * Source: http://stackoverflow.com/questions/13562429/how-many-ways-to-convert-bitmap-to-string-and-vice-versa
 */
public String BitMapToString(Bitmap bitmap){

    ByteArrayOutputStream baos=new  ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG,100, baos);
    byte [] b=baos.toByteArray();
    String temp= Base64.encodeToString(b, Base64.DEFAULT);
    return temp;
}