그리기 가능한 것을 비트맵으로 변환하는 방법은?
저는확실것설싶습다니고정하을을 .Drawable 화면으로 할 수 모든 화면 은 장의배화치 사 경 면 모 배 화 기 면 능 허 이 됩 니 용 다 경 든 있 만 지 수 할 용 으 로 ▁as 니 됩 ▁accept 다 허 ▁wallpaper 용 ▁functions 장 ▁the ▁all ▁but ' , 치Bitmaps만 사용할 수 없습니다.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;
}
비트맵 드로잉 테이블을 비트맵으로 변환합니다.
Drawable d = ImagesArrayList.get(0);
Bitmap bitmap = ((BitmapDrawable)d).getBitmap();
A Drawable 수있 에 그릴 수 .Canvas a 리고a.Canvas로 할 수 .Bitmap:
에 대한 됨)BitmapDrawable는 sand가 sand가 되도록 .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();
안드로이드 스마트폰이 가지고 있습니다.Drawable.toBitmap방법: https://android.github.io/android-ktx/core-ktx/androidx.graphics.drawable/android.graphics.drawable.-drawable/to-bitmap.html
코틀린에서
val bitmap = myDrawable.toBitmap()
비트맵으로 그리기 가능:
Bitmap mIcon = BitmapFactory.decodeResource(context.getResources(),R.drawable.icon);
// mImageView.setImageBitmap(mIcon);
그릴 수 있는 비트맵:
Drawable mDrawable = new BitmapDrawable(getResources(), bitmap);
// mImageView.setDrawable(mDrawable);
아주 간단한
Bitmap tempBMP = BitmapFactory.decodeResource(getResources(),R.drawable.image);
최신 안드로이드x 코어 라이브러리(안드로이드x.core:core-ktx:1.2.0)에는 드로잉 가능한 비트맵으로 변환하는 확장 기능이 있습니다.
그래서 다른 답들을 보고(그리고 사용), 그들이 모두 처리하는 것처럼 보입니다.ColorDrawable그리고.PaintDrawable형편없이. (특히 막대사탕에서)Shaders는 단색 블록이 올바르게 처리되지 않도록 조정되었습니다.
나는 지금 다음 코드를 사용하고 있습니다.
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비트맵으로 바꾸라고 요청하기 전에, 그것은 정확한 크기로 비트맵을 그릴 것입니다!
이게 누군가에게 도움이 될지도...
그림 그리기 가능에서 비트맵으로 다음을 사용합니다.
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);
여기 @Chris가 제공한 멋진 코틀린 버전의 답변이 있습니다.젠킨스 여기: 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
여기 더 나은 해상도가 있습니다.
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());
}
그리기 가능한 비트를 InputStream으로 읽는 방법의 코드
비트맵 비트맵 = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon);
이것은 매번 작동하지 않습니다. 예를 들어 도면층 목록을 그릴 수 있는 경우 null 응답을 제공하므로 도면층을 캔버스에 그린 다음 비트맵으로 저장해야 합니다. 코드 컵 아래를 참조하십시오.
public void drawableToBitMap(Context context, int drawable, int widthPixels, int heightPixels) {
try {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/", "drawable.png");
FileOutputStream fOut = new FileOutputStream(file);
Drawable drw = ResourcesCompat.getDrawable(context.getResources(), drawable, null);
if (drw != null) {
convertToBitmap(drw, widthPixels, heightPixels).compress(Bitmap.CompressFormat.PNG, 100, fOut);
}
fOut.flush();
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private Bitmap convertToBitmap(Drawable drawable, int widthPixels, int heightPixels) {
Bitmap bitmap = Bitmap.createBitmap(widthPixels, heightPixels, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, widthPixels, heightPixels);
drawable.draw(canvas);
return bitmap;
}
위의 코드 저장 다운로드 디렉토리에서 drawable.png로 그릴 수 있습니다.
Android는 직접적이지 않은 솔루션을 제공합니다.BitmapDrawable비트맵을 가져오려면 리소스 ID를 제공해야 합니다.R.drawable.flower_pic에BitmapDrawable그리고 나서 그것을 a에 던집니다.Bitmap.
Bitmap bm = ((BitmapDrawable) getResources().getDrawable(R.drawable.flower_pic)).getBitmap();
BitmapFactory.decodeResource()비트맵의 크기를 자동으로 조정하여 비트맵이 퍼지(fuzzy)로 표시될 수 있습니다.스케일링을 방지하려면 다음을 수행합니다.
BitmapFactory.Options options = new BitmapFactory.Options();
options.inScaled = false;
Bitmap source = BitmapFactory.decodeResource(context.getResources(),
R.drawable.resource_name, options);
또는
InputStream is = context.getResources().openRawResource(R.drawable.resource_name)
bitmap = BitmapFactory.decodeStream(is);
이 code.it 을 사용하면 목표를 달성하는 데 도움이 됩니다.
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;
}
ImageWorker Library는 비트맵을 그리기 가능 또는 base64로 변환하거나 그 반대로 변환할 수 있습니다.
val bitmap: Bitmap? = ImageWorker.convert().drawableToBitmap(sourceDrawable)
실행
프로젝트 레벨 그라들 내
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
응용 프로그램 수준 그라들
dependencies {
implementation 'com.github.1AboveAll:ImageWorker:0.51'
}
또한 외부에서 비트맵/그림판/base64 영상을 저장하고 검색할 수 있습니다.
여기를 확인하세요.https://github.com/1AboveAll/ImageWorker/edit/master/README.md
코틀린을 사용하는 경우 아래 코드를 사용합니다.효과가 있을 것입니다
이미지 경로 사용용
val image = Drawable.createFromPath(path)
val bitmap = (image as BitmapDrawable).bitmap
코틀린에서 가장 쉬운 방법은 다음과 같습니다.
Drawable.toBitmap(width: Int, height: Int, config: Bitmap.Config?): Bitmap
다음과 같이:
val bitmapResult = yourDrawable.toBitmap(1,1,null)
여기서, 그리기 가능한 변수, 리소스 없음, 컨텍스트 없음, ID 없음
// 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);
}
}
}
이 스레드에서 몇 가지 답변을 사용했지만 일부 답변은 예상대로 작동하지 않았습니다(이전 버전에서 작동했을 수도 있음). 하지만 몇 번의 시도와 오류가 발생한 후 확장 기능을 사용하여 내 것을 공유하고 싶었습니다.
val markerOption = MarkerOptions().apply {
position(LatLng(driver.lat, driver.lng))
icon(R.drawabel.your_drawable.toBitmapDescriptor(context))
snippet(driver.driverId.toString())
}
mMap.addMarker(markerOption)
확장 기능은 다음과 같습니다.
fun Int.toBitmapDescriptor(context: Context): BitmapDescriptor {
val vectorDrawable = ResourcesCompat.getDrawable(context.resources, this, context.theme)
val bitmap = vectorDrawable?.toBitmap(
vectorDrawable.intrinsicWidth,
vectorDrawable.intrinsicHeight,
Bitmap.Config.ARGB_8888
)
return BitmapDescriptorFactory.fromBitmap(bitmap!!)
}
언급URL : https://stackoverflow.com/questions/3035692/how-to-convert-a-drawable-to-a-bitmap
'programing' 카테고리의 다른 글
| 8080에서 수신 중인 Oracle XE 구성 요소를 비활성화하는 방법은 무엇입니까? (0) | 2023.06.18 |
|---|---|
| Excel이 워크시트_Change before Workbook_Before Save를 실행하지 않도록 하는 방법은 무엇입니까? (0) | 2023.06.18 |
| Firestore에서 보안 및 인덱스 규칙을 내보내는 방법은 무엇입니까? (0) | 2023.06.18 |
| Visual Studio에서 새 데이터 항목을 추가할 때 EF 6.x DbContext Generator 옵션의 용도 (0) | 2023.06.18 |
| data.frame 열 형식을 문자에서 요인으로 변환 (0) | 2023.06.18 |