android bitmap转icon
时间: 2023-11-11 18:05:53 浏览: 219
android bitmap
要将 Android Bitmap 转换为 Icon,您可以使用以下代码:
```
public static Bitmap getResizedBitmap(Bitmap bitmap, int newWidth, int newHeight) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// create a matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bitmap
matrix.postScale(scaleWidth, scaleHeight);
// recreate the new bitmap
Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, false);
return resizedBitmap;
}
public static void saveImageToInternalStorage(Context context, Bitmap bitmap, String fileName) {
FileOutputStream fos = null;
try {
fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void setIcon(Context context, Bitmap bitmap) {
Bitmap resizedBitmap = getResizedBitmap(bitmap, 192, 192);
String fileName = "app_icon.png";
saveImageToInternalStorage(context, resizedBitmap, fileName);
File file = new File(context.getFilesDir(), fileName);
if (file.exists()) {
String packageName = context.getPackageName();
PackageManager pm = context.getPackageManager();
ComponentName componentName = new ComponentName(packageName, packageName + ".MainActivity");
ActivityInfo activityInfo = null;
try {
activityInfo = pm.getActivityInfo(componentName, PackageManager.GET_META_DATA);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
ApplicationInfo applicationInfo = activityInfo.applicationInfo;
applicationInfo.icon = new BitmapDrawable(context.getResources(), resizedBitmap);
}
}
```
这个代码会将 Bitmap 转换为 Icon,并将其保存到应用程序的内部存储中。请注意,这个代码假定您的应用程序的主要活动的名称是 MainActivity,并且您需要修改它以匹配您的应用程序。
阅读全文