private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { // Raw height and width of image final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { final int halfHeight = height / 2; final int halfWidth = width / 2; // Calculate the largest inSampleSize value that is a power of 2 and keeps both // height and width larger than the requested height and width. while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) { inSampleSize *= 2; } } return inSampleSize; } private Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) { // First decode with inJustDecodeBounds=true to check dimensions final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(res, resId, options); // Calculate inSampleSize options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; return BitmapFactory.decodeResource(res, resId, options); } /** 若直接对FileInputStream进行操作,缩放会出现问题。 FileInputStream是有序的文件流, 两次decodeStream调用会影响文件流的位置属性。 可以通过文件流得到其所对应的文件描述符, 利用BitmapFactory.decodeFileDescriptor()方法进行缩放 */ private Bitmap decodeSampledBitmapFromFileDescriptor(FileDescriptor fd, int reqWidth, int reqHeight) { // First decode with inJustDecodeBounds=true to check dimensions final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFileDescriptor(fd, null, options); // Calculate inSampleSize options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; return BitmapFactory.decodeFileDescriptor(fd, null, options); } /* url to key */ private String hashKeyFromUrl(String url) { try { MessageDigest mDigest = MessageDigest.getInstance("MD5"); mDigest.update(url.getBytes()); StringBuilder sb = new StringBuilder(); byte[] digest = mDigest.digest(); for (int i = 0; i < digest.length; i++) { String hexString = Integer.toHexString(0xFF & digest[i]); if (hexString.length() == 1) { sb.append('0'); } sb.append(hexString); } return sb.toString(); } catch (NoSuchAlgorithmException e) { return String.valueOf(url.hashCode()); } }
LoadBitmap
最新推荐文章于 2022-04-08 00:12:46 发布