下面列出了怎么用android.graphics.BitmapFactory的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Returns the bitmap from the given uri loaded using the given options.
* Returns null on failure.
*/
private Bitmap loadBitmap(Uri uri, BitmapFactory.Options o) throws FileNotFoundException {
if (uri == null || mContext == null) {
throw new IllegalArgumentException("bad argument to loadBitmap");
}
InputStream is = null;
try {
is = mContext.getContentResolver().openInputStream(uri);
return BitmapFactory.decodeStream(is, null, o);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException t) {
Log.w(LOG_TAG, "close fail ", t);
}
}
}
}
@Override
protected void onPostExecute(File result) {
// Remember the written file in case the filter or contrast is changed
_outputpath = result.toString();
// Show the processed image
Bitmap bm = BitmapFactory.decodeFile(result.toString());
if (bm != null) {
_imageview.setImageBitmap(bm);
}
else {
Log.w(TAG, "Failed to read created image " + result.toString());
}
if (_task == this) {
_task = null;
}
super.onPostExecute(result);
}
public void Init() {
dp = getResources().getDimension(R.dimen.triangle_dp);
bitmapScale = BitmapFactory.decodeResource(getResources(),
R.drawable.triangle_icon_round_calibration);
brWidth = bitmapScale.getWidth();
brHeight = bitmapScale.getHeight();
WidthCenter = getWidth() / 2;
HeightCenter = getHeight() / 2;
zoom(0f);
rectf = new RectF();
rectf.set(dp * 0.1f, dp * 0.1f, getWidth() - dp * 0.1f, getHeight()
- dp * 0.1f);
}
public FollowAdapter(PullToRefreshView view) {
super(view);
curPage = -1;
hasNext = true;
map = new HashMap<String, Following>();
follows = new ArrayList<Following>();
llHeader = new PRTHeader(getContext());
int resId = getBitmapRes(getContext(), "auth_follow_cb_chd");
if (resId > 0) {
bmChd = BitmapFactory.decodeResource(view.getResources(), resId);
}
resId = getBitmapRes(getContext(), "auth_follow_cb_unc");
if (resId > 0) {
bmUnch = BitmapFactory.decodeResource(view.getResources(), resId);
}
}
/**
* Decode and sample down a bitmap from a file input stream to the requested width and height.
*
* @param fileDescriptor The file descriptor to read from
* @param reqWidth The requested width of the resulting bitmap
* @param reqHeight The requested height of the resulting bitmap
* @return A bitmap sampled down from the original with the same aspect ratio and dimensions
* that are equal to or greater than the requested width and height
*/
public static Bitmap decodeSampledBitmapFromDescriptor(
FileDescriptor fileDescriptor, int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
}
private void returnPickIcon() {
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeResource(getResources(), iconBean.getId());
} catch (Exception e) {
e.printStackTrace();
}
Intent intent = new Intent();
if (bitmap != null) {
intent.putExtra("icon", bitmap);
intent.putExtra("android.intent.extra.shortcut.ICON_RESOURCE", iconBean.getId());
intent.setData(Uri.parse("android.resource://" + getContext().getPackageName()
+ "/" + String.valueOf(iconBean.getId())));
getActivity().setResult(Activity.RESULT_OK, intent);
} else {
getActivity().setResult(Activity.RESULT_CANCELED, intent);
}
getActivity().finish();
}
private void loadPhotoSphere() {
//This could take a while. Should do on a background thread, but fine for current example
VrPanoramaView.Options options = new VrPanoramaView.Options();
InputStream inputStream = null;
AssetManager assetManager = getAssets();
try {
inputStream = assetManager.open("openspace.jpg");
options.inputType = VrPanoramaView.Options.TYPE_MONO;
mVrPanoramaView.loadImageFromBitmap(BitmapFactory.decodeStream(inputStream), options);
inputStream.close();
} catch (IOException e) {
Log.e("Tuts+", "Exception in loadPhotoSphere: " + e.getMessage() );
}
}
public void bind(@NonNull FavoriteItemModel favoriteItemModel) {
mTextView.setText(favoriteItemModel.getTitle());
mTextView.setAlpha(favoriteItemModel.isDisabled() ? 0.4f : 1.0f);
if (favoriteItemModel.getImageResource() != null) {
BlackWhiteInvertTransformation transform = new BlackWhiteInvertTransformation(Invert.BLACK_TO_WHITE);
Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(), favoriteItemModel.getImageResource());
if(favoriteItemModel.getKeepImageColor()) {
mImageView.setImageBitmap(bitmap);
}
else {
mImageView.setImageBitmap(transform.transform(bitmap));
}
} else {
ImageManager.with(mContext)
.putSmallDeviceImage((DeviceModel) favoriteItemModel.getModel())
.withTransformForStockImages(new BlackWhiteInvertTransformation(Invert.BLACK_TO_WHITE))
.withPlaceholder(R.drawable.device_list_placeholder)
.withError(R.drawable.device_list_placeholder)
.noUserGeneratedImagery()
.into(mImageView)
.execute();
}
mImageView.setAlpha(favoriteItemModel.isDisabled() ? 0.4f : 1.0f);
}
@Override
public void setPageIcon(int position, ImageView image) {
if (position == 0) {
image.setImageResource(R.drawable.icon_face_click);
return;
}
File file = new File(datas.get(position - 1));
String path = null;
for (int i = 0; i < file.list().length; i++) {
path = file.list()[i];
if (path.endsWith(".png") || path.endsWith(".jpg") || path.endsWith(".jpeg")) {
break;
}
}
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath() + "/" + path);
image.setImageBitmap(bitmap);
}
public static 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) {
// Calculate ratios of height and width to requested height and width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
/**
* 压缩bitmp到目标大小(质量压缩)
* @param bitmap
* @param needRecycle
* @param maxSize
* @return
*/
public static Bitmap compressBitmap(Bitmap bitmap, boolean needRecycle, long maxSize) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
int options = 100;
while (baos.toByteArray().length > maxSize) {
baos.reset();//重置baos即清空baos
bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);
options -= 10;//每次都减少10
}
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
Bitmap bm = BitmapFactory.decodeStream(isBm, null, null);
if(needRecycle) {
bitmap.recycle();
}
bitmap = bm;
return bitmap;
}
private boolean verifyImage(Uri uri) {
InputStream inputStream;
try {
inputStream = getActivity().getContentResolver().openInputStream(uri);
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(inputStream, null, options);
if (options.outWidth > MAX_IAMGE_SIZE || options.outHeight > MAX_IAMGE_SIZE)
return false;
return true;
}
/**
* Loads a Bitmap from the given URI and scales and crops it to the given size
*
* @param uri The URI to load the Bitmap from
* @param size The size the final Bitmap should be
* @return
*/
private Bitmap loadCroppedBitmapFromUri(Uri uri, int size) {
File bitmapFile = FileUtils.getFile(getActivity(), uri);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(bitmapFile.getPath(), options); // TODO: Handle null pointers.
options.inSampleSize = calculateSampleSize(options, size, size);
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(bitmapFile.getPath(), options);
if (bitmap == null) {
Utils.d("Bitmap loading failed!");
return null;
}
if (bitmap.getHeight() > size || bitmap.getWidth() > size) {
bitmap = Utils.crop(bitmap, size, size);
}
return bitmap;
}
/**
* 压缩指定路径的图片,并得到图片对象
*
* @param path
* @return
*/
private Bitmap compressBitmapFromFile(String path) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(path, options);
options.inJustDecodeBounds = false;
int width = options.outWidth;
int height = options.outHeight;
float widthRadio = 1080f;
float heightRadio = 1920f;
int inSampleSize = 1;
if (width > height && width > widthRadio) {
inSampleSize = (int) (width * 1.0f / widthRadio);
} else if (width < height && height > heightRadio) {
inSampleSize = (int) (height * 1.0f / heightRadio);
}
if (inSampleSize <= 0) {
inSampleSize = 1;
}
options.inSampleSize = inSampleSize;
bitmap = BitmapFactory.decodeFile(path, options);
return compressBitmap(bitmap);
}
private boolean addTitleSummaryAndThumb(WXMediaMessage msg, Bundle params) {
if (params.containsKey(WXShareEntity.KEY_WX_TITLE)) {
msg.title = params.getString(WXShareEntity.KEY_WX_TITLE);
}
if (params.containsKey(WXShareEntity.KEY_WX_SUMMARY)) {
msg.description = params.getString(WXShareEntity.KEY_WX_SUMMARY);
}
if (params.containsKey(WXShareEntity.KEY_WX_IMG_LOCAL) || params.containsKey(WXShareEntity.KEY_WX_IMG_RES)) {
Bitmap bitmap;
if (params.containsKey(WXShareEntity.KEY_WX_IMG_LOCAL)) {//分为本地文件和应用内资源图片
String imgUrl = params.getString(WXShareEntity.KEY_WX_IMG_LOCAL);
if (notFoundFile(imgUrl)) {
return true;
}
bitmap = BitmapFactory.decodeFile(imgUrl);
} else {
bitmap = BitmapFactory.decodeResource(activity.getResources(), params.getInt(WXShareEntity.KEY_WX_IMG_RES));
}
msg.thumbData = SocialUtil.bmpToByteArray(bitmap, true);
}
return false;
}
public static Bitmap decodeFile(String pathName, int reqWidth, int reqHeight) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(pathName, options);
options.inSampleSize = Util.calculateInSampleSize(options, reqWidth, reqHeight);
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
options.inMutable = true;
Bitmap inBitmap = GlideBitmapPool.getBitmap(options.outWidth, options.outHeight, options.inPreferredConfig);
if (inBitmap != null && Util.canUseForInBitmap(inBitmap, options)) {
options.inBitmap = inBitmap;
}
}
options.inJustDecodeBounds = false;
try {
return BitmapFactory.decodeFile(pathName, options);
} catch (Exception e) {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
options.inBitmap = null;
}
return BitmapFactory.decodeFile(pathName, options);
}
}
private static Bitmap decodeSampledBitmapFromUrl(String url, int reqWidth, int reqHeight) throws IOException {
// First decode with inJustDecodeBounds=true to check dimensions
final Options options = new Options();
options.inJustDecodeBounds = true;
InputStream stream = fetchStream(url);
BitmapFactory.decodeStream(stream, null, options);
stream.close();
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
stream = fetchStream(url);
Bitmap bitmap = BitmapFactory.decodeStream(stream, null, options);
stream.close();
return bitmap;
}
public static Bitmap createBitmap(int width, int height, Bitmap.Config config) {
Bitmap bitmap;
if (Build.VERSION.SDK_INT < 21) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inDither = true;
options.inPreferredConfig = config;
options.inPurgeable = true;
options.inSampleSize = 1;
options.inMutable = true;
byte[] array = jpegData.get();
array[76] = (byte) (height >> 8);
array[77] = (byte) (height & 0x00ff);
array[78] = (byte) (width >> 8);
array[79] = (byte) (width & 0x00ff);
bitmap = BitmapFactory.decodeByteArray(array, 0, array.length, options);
Utilities.pinBitmap(bitmap);
bitmap.setHasAlpha(true);
bitmap.eraseColor(0);
} else {
bitmap = Bitmap.createBitmap(width, height, config);
}
if (config == Bitmap.Config.ARGB_8888 || config == Bitmap.Config.ARGB_4444) {
bitmap.eraseColor(Color.TRANSPARENT);
}
return bitmap;
}
/**
* 开始进行Gif生成
*
* @param context 上下文对象.
* @param path Gif保存的路径.
* @param width 宽度.
* @param height 高度.
* @param typedArray Android资源数组对象.
* @return 是否成功.
*/
public boolean encode(final Context context, final String path, final int width, final int height, final TypedArray typedArray) {
check(width, height, path);
if (typedArray == null || typedArray.length() == 0) {
return false;
}
int state;
int[] pixels = new int[width * height];
state = init(path, width, height, mColor, mQuality, mDelay / 10);
if (state != 0) {
// 失败
return false;
}
for (int i = 0; i < typedArray.length(); i++) {
Bitmap bitmap;
bitmap = BitmapFactory.decodeResource(context.getResources(), typedArray.getResourceId(i, -1));
if (width < bitmap.getWidth() || height < bitmap.getHeight()) {
bitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);
}
bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
addFrame(pixels);
bitmap.recycle();
}
close();
return true;
}
@Override
public View onCreateView(LayoutInflater inflater,ViewGroup parent,Bundle savedInstanceState){
View ret = inflater.inflate(R.layout.layout_main_menu,parent,false);
ret.setBackgroundColor(Color.TRANSPARENT);
theList = (RecyclerView) ret.findViewById(R.id.id_list_view_main_menu);
theList.setAdapter(MenuAdapter.getStaticInstance(getActivity()).getMainMenuAdapter());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
theList.setLayoutManager(new LinearLayoutManager(getContext()));
} else {
theList.setLayoutManager(new LinearLayoutManager(parent.getContext()));
}
// theList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
currentItemIndex = 0;
MenuAdapter.getStaticInstance(null).HighlightItem(0);
imageView = (ImageView) ret.findViewById(R.id.id_main_menu_image);
nowPlayingPage = (LinearLayout) ret.findViewById(R.id.id_mainmenu_nowplaying);
imageView.setImageBitmap(BitmapFactory.decodeResource(getResources(),menuIcons[0]));
rightPanelContent = (FrameLayout) ret.findViewById(R.id.right_panel_content);
albumStack = (AlbumStack) ret.findViewById(R.id.id_album_stack);
albumStack.init();
leftPanel = (FrameLayout) ret.findViewById(R.id.main_menu_left);
rightPanel = (LinearLayout) ret.findViewById(R.id.main_menu_right);
npTitle = (TextView) ret.findViewById(R.id.id_mainmenu_nowplaying_title);
npArtist = (TextView) ret.findViewById(R.id.id_mainmenu_nowplaying_artist);
loadTheme();
return ret;
}
public static Bitmap getSmallBitmap(String filePath, int reqWidth, int reqHeight) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(filePath, options);
}
private void checkVisibilityUserIcon() {
UserCustomData userCustomData = Utils.customDataToObject(AppSession.getSession().getUser().getCustomData());
if (!TextUtils.isEmpty(userCustomData.getAvatarUrl())) {
loadLogoActionBar(userCustomData.getAvatarUrl());
} else {
setActionBarIcon(MediaUtils.getRoundIconDrawable(this,
BitmapFactory.decodeResource(getResources(), R.drawable.placeholder_user)));
}
}
/**
* 获取 Bitmap
* @param inputStream {@link InputStream}
* @param maxWidth 最大宽度
* @param maxHeight 最大高度
* @return {@link Bitmap}
*/
public static Bitmap getBitmap(final InputStream inputStream, final int maxWidth, final int maxHeight) {
if (inputStream == null) return null;
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(inputStream, null, options);
options.inSampleSize = BitmapUtils.calculateInSampleSize(options, maxWidth, maxHeight);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeStream(inputStream, null, options);
} catch (Exception e) {
LogPrintUtils.eTag(TAG, e, "getBitmap");
return null;
}
}
/**
* Get width and height of the bitmap specified with the resource id.
*
* @param res resource accessor.
* @param resId the resource id of the drawable.
* @return the drawable bitmap size.
*/
public static Point getSize(Resources res, int resId) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
int width = options.outWidth;
int height = options.outHeight;
return new Point(width, height);
}
private Bitmap parse(byte[] byteArray) throws OutOfMemoryError {
BitmapFactory.Options decodeOptions = new BitmapFactory.Options();
Bitmap bitmap;
if (maxWidth == 0 && maxHeight == 0) {
decodeOptions.inPreferredConfig = decodeConfig;
bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length, decodeOptions);
} else {
decodeOptions.inJustDecodeBounds = true;
BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length, decodeOptions);
int actualWidth = decodeOptions.outWidth;
int actualHeight = decodeOptions.outHeight;
int desiredWidth = getResizedDimension(maxWidth, maxHeight, actualWidth, actualHeight, scaleType);
int desiredHeight = getResizedDimension(maxHeight, maxWidth, actualHeight, actualWidth, scaleType);
decodeOptions.inJustDecodeBounds = false;
decodeOptions.inSampleSize = findBestSampleSize(actualWidth, actualHeight, desiredWidth, desiredHeight);
Bitmap tempBitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length, decodeOptions);
if (tempBitmap != null && (tempBitmap.getWidth() > desiredWidth || tempBitmap.getHeight() > desiredHeight)) {
bitmap = Bitmap.createScaledBitmap(tempBitmap, desiredWidth, desiredHeight, true);
tempBitmap.recycle();
} else {
bitmap = tempBitmap;
}
}
return bitmap;
}
public static Bitmap compressByQuality(final Bitmap src,
@IntRange(from = 0, to = 100) final int quality,
final boolean recycle) {
if (isEmptyBitmap(src)) return null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
src.compress(Bitmap.CompressFormat.JPEG, quality, baos);
byte[] bytes = baos.toByteArray();
if (recycle && !src.isRecycled()) src.recycle();
return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
}
private void handleCrop(int resultCode, Intent result) {
if (resultCode == RESULT_OK) {
Uri pp = Crop.getOutput(result);
String p1 = pp.toString();
p = comman.compressImage(ProfileSetting.this, p1);
selectedImage = BitmapFactory.decodeFile(p);
imagePhoto.setImageBitmap(selectedImage);
encodeimage = comman.encodeTobase64(selectedImage);
callImagechange(encodeimage);
} else if (resultCode == Crop.RESULT_ERROR) {
Toast.makeText(this, Crop.getError(result).getMessage(), Toast.LENGTH_SHORT).show();
}
}
public static 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);
}
public Bitmap getTransformedBitmap(byte[] data) {
Log.d(TAG, "Picture taken!!");
Bitmap b = rotateBitmap(BitmapFactory.decodeByteArray(data, 0, data.length), mCameraRotation);
int w = b.getWidth();
int h = b.getHeight();
int sw = mCameraPreview.getWidth();
int sh = mCameraPreview.getHeight();
/**
* Map screen coordinates to image coordinates
* Assumes aspect ratios of preview and image are the same
*/
Point[] coords = mHLView.getCoords();
float[] src = new float[coords.length * 2];
for (int i = 0; i < coords.length; i++) {
Point coord = coords[i];
src[i * 2 + 0] = (coord.x / (float) sw) * w;
src[i * 2 + 1] = (coord.y / (float) sh) * h;
}
Bitmap target = Bitmap.createBitmap(b.getWidth(), b.getHeight(), b.getConfig());
int tw = target.getWidth();
int th = target.getHeight();
Canvas canvas = new Canvas(target);
Matrix m = new Matrix();
m.setPolyToPoly(src, 0, new float[]{0, 0, tw, 0, tw, th, 0, th}, 0, 4);
canvas.drawBitmap(b, m, null);
return target;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.frame);
final BubbleView bubbleView = new BubbleView(getApplicationContext(),
BitmapFactory.decodeResource(getResources(), R.drawable.b128));
relativeLayout.addView(bubbleView);
}