android 图片处理

2 篇文章 0 订阅
1 篇文章 0 订阅

1:图片压缩,将大图非失真压缩,改变大小,适用图片上传,以下函数最终大小压缩至50k,可适当调整该值

private String getImageData(String pathName){
	try {			
		Bitmap bmp = CommonUtils.decodeSampledBitmapFromFile(pathName, 480, 800);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
		int options = 100;
		System.out.println(" 压缩前baos.toByteArray大小: " + baos.toByteArray().length);
		while ( baos.toByteArray().length / 1024 > 50) {
			baos.reset();
			bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
			options -= 10;
		}
		if(bmp != null && !bmp.isRecycled()){
			bmp.isRecycled();
			bmp = null;
		}
		System.out.println(" 压缩后baos.toByteArray()大小: " + baos.toByteArray().length);

		return Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT);
	} catch (Exception e) {
	}
	return null;
}
/**
     * 根据计算的inSampleSize,得到压缩后图片
     *
     * @param pathName
     * @param reqWidth
     * @param reqHeight
     * @return
     */
    public static Bitmap decodeSampledBitmapFromFile(String pathName,int reqWidth, int reqHeight) {
    	try {
    		// 第一次解析将inJustDecodeBounds设置为true,来获取图片大小
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inPreferredConfig = Bitmap.Config.RGB_565;
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(pathName, options);
            
            // 调用上面定义的方法计算inSampleSize值
            options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
            // 使用获取到的inSampleSize值再次解析图片
            options.inJustDecodeBounds = false;
            return BitmapFactory.decodeFile(pathName, options);
		} catch (Exception e) {
			
			System.out.println("decodeSampledBitmapFromFile err in : " + e.toString());
		}
        
		return null;
    }
	
    /**
     * 计算inSampleSize,用于压缩图片
     *
     * @param options
     * @param reqWidth
     * @param reqHeight
     * @return
     */
    private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // 源图片的宽度
        int width = options.outWidth;
        int height = options.outHeight;
        int inSampleSize = 1;

        // 通过之前的计算方法,在加载类似400*4000这种长图时会内存溢出
        if (width > reqWidth || height > reqHeight) {
            int widthRadio = Math.round(width * 1.0f / reqWidth);
            int heightRadio = Math.round(height * 1.0f / reqHeight);

            inSampleSize = Math.max(widthRadio, heightRadio);
        }

        return inSampleSize;
    }

2  通过网络图片地址下载保存图片:

/**
	destUrl:图片网络地址
	path:图片保存路径
	*/
	public static boolean saveToFile(String destUrl, String path) {
		FileOutputStream fos = null;
		BufferedInputStream bis = null;
		HttpURLConnection httpUrl = null;
		URL url = null;
		int BUFFER_SIZE = 1024 * 4;
		byte[] buf = new byte[BUFFER_SIZE];
		int size = 0;
		try {
			url = new URL(destUrl);
			httpUrl = (HttpURLConnection) url.openConnection();
			httpUrl.connect();
			bis = new BufferedInputStream(httpUrl.getInputStream());
			fos = new FileOutputStream(path);
			while ((size = bis.read(buf)) != -1) {
				fos.write(buf, 0, size);
			}
			fos.flush();
			
			try {
				fos.close();
				bis.close();
				httpUrl.disconnect();
				return true;
			} catch (IOException e) {
				return false;
			} catch (NullPointerException e) {
				return false;
			}
			
		} catch (IOException e) {
			return false;
		} catch (ClassCastException e) {
			return false;
		} /*finally {
			try {
				fos.close();
				bis.close();
				httpUrl.disconnect();
			} catch (IOException e) {
				return false;
			} catch (NullPointerException e) {
				return false;
			}
			
		}
		return true;*/
	}   

3 节约内存加载背景图片

方式一

    //加载背景图片
	String url = "drawable://" + R.drawable.view_bg;
	DisplayImageOptions options = new DisplayImageOptions.Builder()
        .showImageOnFail(R.drawable.view_bg)
        .cacheInMemory(false)
        .bitmapConfig(Bitmap.Config.RGB_565)
        .build();
	ImageLoader.getInstance().displayImage(url, imageView, options);

方式二

Glide.with(this)
	.load(R.drawable.welcome_bg)
	.diskCacheStrategy( DiskCacheStrategy.NONE)
	.into(imageView);

 

4 本地图片路径转化为字节数组(不做压缩)

 

//原图上传不做任何处理
	public byte[] imageData(String path) {
        try {
        	byte[] buffer = new byte[1024];
        	int len = -1;
            InputStream inStream = new FileInputStream(path);
    		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
//    		while ((len = inStream.read(buffer)) != -1) {
    		while ((len = inStream.read(buffer, 0, 1024)) != -1) {
    			outStream.write(buffer, 0, len);
    		}
    		byte[] data = outStream.toByteArray();
    		outStream.close();
    		inStream.close();
    		
    		DebugUtils.debug(TAG, "上传图片大小: "  + data.length);
    		return data;
    		
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return null;
    }

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值