Jawaban:
quality
?
Semoga ini akan membantu Anda:
//create a file to write bitmap data
File f = new File(context.getCacheDir(), filename);
f.createNewFile();
//Convert bitmap to byte array
Bitmap bitmap = your bitmap;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
//write the bytes in file
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();
CompressFormat.JPEG
. Sesuai google doco: Petunjuk untuk kompresor, 0-100. 0 artinya kompres untuk ukuran kecil, 100 artinya kompres untuk kualitas maksimal. Beberapa format, seperti PNG yang lossless, akan mengabaikan pengaturan kualitas
ByteArrayOutputStream
, dapatkan array byte dari itu, lalu tulis array ke a FileOutputStream
? Mengapa tidak hanya di FileOutputStream
dalam Bitmap.compress
?
File file = new File("path");
OutputStream os = new BufferedOutputStream(new FileOutputStream(file));
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
os.close();
File()
konstruktor Anda .
Mengubah Bitmap
menjadi File
perlu dilakukan di latar belakang (BUKAN DI BENANG UTAMA) itu menggantung UI khususnya jika ukurannya bitmap
besar
File file;
public class fileFromBitmap extends AsyncTask<Void, Integer, String> {
Context context;
Bitmap bitmap;
String path_external = Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg";
public fileFromBitmap(Bitmap bitmap, Context context) {
this.bitmap = bitmap;
this.context= context;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
// before executing doInBackground
// update your UI
// exp; make progressbar visible
}
@Override
protected String doInBackground(Void... params) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
file = new File(Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg");
try {
FileOutputStream fo = new FileOutputStream(file);
fo.write(bytes.toByteArray());
fo.flush();
fo.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
// back to main thread after finishing doInBackground
// update your UI or take action after
// exp; make progressbar gone
sendFile(file);
}
}
Menyebutnya
new fileFromBitmap(my_bitmap, getApplicationContext()).execute();
Anda HARUS menggunakan file
dalam onPostExecute
.
Untuk mengubah direktori file
untuk disimpan dalam baris ganti cache:
file = new File(Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg");
dengan:
file = new File(context.getCacheDir(), "temporary_file.jpg");
Sebagian besar jawaban terlalu panjang atau terlalu pendek tidak memenuhi tujuan. Bagi mereka yang mencari kode Java atau Kotlin untuk mengonversi bitmap ke Objek File. Berikut adalah artikel rinci yang saya tulis tentang topik tersebut. Ubah Bitmap ke File di Android
public static File bitmapToFile(Context context,Bitmap bitmap, String fileNameToSave) { // File name like "image.png"
//create a file to write bitmap data
File file = null;
try {
file = new File(Environment.getExternalStorageDirectory() + File.separator + fileNameToSave);
file.createNewFile();
//Convert bitmap to byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0 , bos); // YOU can also save it in JPEG
byte[] bitmapdata = bos.toByteArray();
//write the bytes in file
FileOutputStream fos = new FileOutputStream(file);
fos.write(bitmapdata);
fos.flush();
fos.close();
return file;
}catch (Exception e){
e.printStackTrace();
return file; // it will return null
}
}
Semoga ini bisa membantu Anda
class MainActivity: AppCompatActivity () {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Get the bitmap from assets and display into image view
val bitmap = assetsToBitmap("tulip.jpg")
// If bitmap is not null
bitmap?.let {
image_view_bitmap.setImageBitmap(bitmap)
}
// Click listener for button widget
button.setOnClickListener{
if(bitmap!=null){
// Save the bitmap to a file and display it into image view
val uri = bitmapToFile(bitmap)
image_view_file.setImageURI(uri)
// Display the saved bitmap's uri in text view
text_view.text = uri.toString()
// Show a toast message
toast("Bitmap saved in a file.")
}else{
toast("bitmap not found.")
}
}
}
// Method to get a bitmap from assets
private fun assetsToBitmap(fileName:String):Bitmap?{
return try{
val stream = assets.open(fileName)
BitmapFactory.decodeStream(stream)
}catch (e:IOException){
e.printStackTrace()
null
}
}
// Method to save an bitmap to a file
private fun bitmapToFile(bitmap:Bitmap): Uri {
// Get the context wrapper
val wrapper = ContextWrapper(applicationContext)
// Initialize a new file instance to save bitmap object
var file = wrapper.getDir("Images",Context.MODE_PRIVATE)
file = File(file,"${UUID.randomUUID()}.jpg")
try{
// Compress the bitmap and save in jpg format
val stream:OutputStream = FileOutputStream(file)
bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream)
stream.flush()
stream.close()
}catch (e:IOException){
e.printStackTrace()
}
// Return the saved bitmap uri
return Uri.parse(file.absolutePath)
}
}
FileOutputStream
, hanya sebuah File. Apakah ada jalan keluarnya?