드로어 블을 비트 맵으로 변환하는 방법은 무엇입니까?
특정 Drawable
기기의 배경 화면 을 설정하고 싶지만 모든 배경 화면 기능은 Bitmap
s 만 허용 합니다. WallpaperManager
2.1 이전이므로 사용할 수 없습니다 .
또한 내 드로어 블은 웹에서 다운로드되며 R.drawable
.
이 코드가 도움이됩니다.
Bitmap icon = BitmapFactory.decodeResource(context.getResources(),
R.drawable.icon_resource);
여기에 이미지가 다운로드되는 버전이 있습니다.
String name = c.getString(str_url);
URL url_value = new URL(name);
ImageView profile = (ImageView)v.findViewById(R.id.vdo_icon);
if (profile != null) {
Bitmap mIcon1 =
BitmapFactory.decodeStream(url_value.openConnection().getInputStream());
profile.setImageBitmap(mIcon1);
}
public static Bitmap drawableToBitmap (Drawable drawable) {
Bitmap bitmap = null;
if (drawable instanceof BitmapDrawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
if(bitmapDrawable.getBitmap() != null) {
return bitmapDrawable.getBitmap();
}
}
if(drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel
} else {
bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
이것은 BitmapDrawable을 Bitmap으로 변환합니다.
Drawable d = ImagesArrayList.get(0);
Bitmap bitmap = ((BitmapDrawable)d).getBitmap();
A Drawable
는에 그려 질 수 있고 Canvas
a Canvas
는에 의해 뒷받침 될 수 있습니다 Bitmap
.
( BitmapDrawable
s에 대한 빠른 변환을 처리 하고 Bitmap
생성 된 파일이 유효한 크기 를 갖도록 업데이트 됨 )
public static Bitmap drawableToBitmap (Drawable drawable) {
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable)drawable).getBitmap();
}
int width = drawable.getIntrinsicWidth();
width = width > 0 ? width : 1;
int height = drawable.getIntrinsicHeight();
height = height > 0 ? height : 1;
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
방법 1 : 다음과 같이 비트 맵으로 직접 변환 할 수 있습니다.
Bitmap myLogo = BitmapFactory.decodeResource(context.getResources(), R.drawable.my_drawable);
방법 2 : 리소스를 드로어 블로 변환 할 수도 있으며 여기서 이와 같은 비트 맵을 얻을 수 있습니다.
Bitmap myLogo = ((BitmapDrawable)getResources().getDrawable(R.drawable.logo)).getBitmap();
들어 API> (22) getDrawable
방법은 이동 ResourcesCompat
그래서 당신은 같은 것을 할 것을위한 클래스
Bitmap myLogo = ((BitmapDrawable) ResourcesCompat.getDrawable(context.getResources(), R.drawable.logo, null)).getBitmap();
아주 간단
Bitmap tempBMP = BitmapFactory.decodeResource(getResources(),R.drawable.image);
따라서 다른 답변을 살펴보고 사용하면 모두 처리 ColorDrawable
하고 PaintDrawable
나쁘게 보입니다 . (특히 롤리팝에서) Shader
s가 조정되어 단색 블록이 올바르게 처리되지 않은 것 같습니다.
지금 다음 코드를 사용하고 있습니다.
public static Bitmap drawableToBitmap(Drawable drawable) {
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
}
// We ask for the bounds if they have been set as they would be most
// correct, then we check we are > 0
final int width = !drawable.getBounds().isEmpty() ?
drawable.getBounds().width() : drawable.getIntrinsicWidth();
final int height = !drawable.getBounds().isEmpty() ?
drawable.getBounds().height() : drawable.getIntrinsicHeight();
// Now we check we are > 0
final Bitmap bitmap = Bitmap.createBitmap(width <= 0 ? 1 : width, height <= 0 ? 1 : height,
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
다른 사람과는 달리, 당신이 호출하면 setBounds
온 Drawable
비트 맵으로 바꿀 것을 요청하기 전에, 그것은 올바른 크기의 비트 맵을 그릴 것입니다!
어쩌면 이것은 누군가를 도울 것입니다 ...
PictureDrawable에서 Bitmap으로 다음을 사용합니다.
private Bitmap pictureDrawableToBitmap(PictureDrawable pictureDrawable){
Bitmap bmp = Bitmap.createBitmap(pictureDrawable.getIntrinsicWidth(), pictureDrawable.getIntrinsicHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bmp);
canvas.drawPicture(pictureDrawable.getPicture());
return bmp;
}
... 다음과 같이 구현됩니다.
Bitmap bmp = pictureDrawableToBitmap((PictureDrawable) drawable);
여기에 더 나은 해상도가 있습니다.
public static Bitmap drawableToBitmap (Drawable drawable) {
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable)drawable).getBitmap();
}
Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
public static InputStream bitmapToInputStream(Bitmap bitmap) {
int size = bitmap.getHeight() * bitmap.getRowBytes();
ByteBuffer buffer = ByteBuffer.allocate(size);
bitmap.copyPixelsToBuffer(buffer);
return new ByteArrayInputStream(buffer.array());
}
Code from How to read drawable bits as InputStream
Here is the nice Kotlin version of the answer provided by @Chris.Jenkins here: https://stackoverflow.com/a/27543712/1016462
fun Drawable.toBitmap(): Bitmap {
if (this is BitmapDrawable) {
return bitmap
}
val width = if (bounds.isEmpty) intrinsicWidth else bounds.width()
val height = if (bounds.isEmpty) intrinsicHeight else bounds.height()
return Bitmap.createBitmap(width.nonZero(), height.nonZero(), Bitmap.Config.ARGB_8888).also {
val canvas = Canvas(it)
setBounds(0, 0, canvas.width, canvas.height)
draw(canvas)
}
}
private fun Int.nonZero() = if (this <= 0) 1 else this
Android provides a non straight foward solution: BitmapDrawable
. To get the Bitmap , we'll have to provide the resource id R.drawable.flower_pic
to the a BitmapDrawable
and then cast it to a Bitmap
.
Bitmap bm = ((BitmapDrawable) getResources().getDrawable(R.drawable.flower_pic)).getBitmap();
Use this code.it will help you for achieving your goal.
Bitmap bmp=BitmapFactory.decodeResource(getResources(), R.drawable.profileimage);
if (bmp!=null) {
Bitmap bitmap_round=getRoundedShape(bmp);
if (bitmap_round!=null) {
profileimage.setImageBitmap(bitmap_round);
}
}
public Bitmap getRoundedShape(Bitmap scaleBitmapImage) {
int targetWidth = 100;
int targetHeight = 100;
Bitmap targetBitmap = Bitmap.createBitmap(targetWidth,
targetHeight,Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(targetBitmap);
Path path = new Path();
path.addCircle(((float) targetWidth - 1) / 2,
((float) targetHeight - 1) / 2,
(Math.min(((float) targetWidth),
((float) targetHeight)) / 2),
Path.Direction.CCW);
canvas.clipPath(path);
Bitmap sourceBitmap = scaleBitmapImage;
canvas.drawBitmap(sourceBitmap,
new Rect(0, 0, sourceBitmap.getWidth(),
sourceBitmap.getHeight()),
new Rect(0, 0, targetWidth, targetHeight), new Paint(Paint.FILTER_BITMAP_FLAG));
return targetBitmap;
}
BitmapFactory.decodeResource()
automatically scales the bitmap, so your bitmap may turn out fuzzy. To prevent scaling, do this:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inScaled = false;
Bitmap source = BitmapFactory.decodeResource(context.getResources(),
R.drawable.resource_name, options);
or
InputStream is = context.getResources().openRawResource(R.drawable.resource_name)
bitmap = BitmapFactory.decodeStream(is);
// get image path from gallery
protected void onActivityResult(int requestCode, int resultcode, Intent intent) {
super.onActivityResult(requestCode, resultcode, intent);
if (requestCode == 1) {
if (intent != null && resultcode == RESULT_OK) {
Uri selectedImage = intent.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
filePath = cursor.getString(columnIndex);
//display image using BitmapFactory
cursor.close(); bmp = BitmapFactory.decodeFile(filepath);
iv.setBackgroundResource(0);
iv.setImageBitmap(bmp);
}
}
}
ImageWorker Library can convert bitmap to drawable or base64 and vice versa.
val bitmap: Bitmap? = ImageWorker.convert().drawableToBitmap(sourceDrawable)
Implementation
In Project Level Gradle
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
In Application Level Gradle
dependencies {
implementation 'com.github.1AboveAll:ImageWorker:0.51'
}
You can also store and retrieve bitmaps/drawables/base64 images from external.
Check here. https://github.com/1AboveAll/ImageWorker/edit/master/README.md
if you are using kotlin the use below code. it'll work
// for using image path
val image = Drawable.createFromPath(path)
val bitmap = (image as BitmapDrawable).bitmap
android-ktx has Drawable.toBitmap
method: https://android.github.io/android-ktx/core-ktx/androidx.graphics.drawable/android.graphics.drawable.-drawable/to-bitmap.html
From Kotlin
val bitmap = myDrawable.toBitmap()
참고URL : https://stackoverflow.com/questions/3035692/how-to-convert-a-drawable-to-a-bitmap
'programing' 카테고리의 다른 글
Java 클래스에서 표준 이름, 단순 이름 및 클래스 이름의 차이점은 무엇입니까? (0) | 2020.09.28 |
---|---|
: :( 이중 콜론) 연산자 (Java 8) (0) | 2020.09.28 |
생성자와 ngOnInit의 차이점 (0) | 2020.09.28 |
Swift의 #pragma 마크? (0) | 2020.09.28 |
외부 JAR에서 "오류 1로 인해 Dalvik 형식으로 변환 실패" (0) | 2020.09.28 |