Giới thiệu
Ví dụ này minh họa cách chuyển đổi Bitmap sang byte[] (mảng byte) trong Android, hữu ích khi lưu ảnh vào database, gửi qua network, hoặc nén ảnh.
Các bước thực hiện
Bước 1: Tạo dự án mới
Mở Android Studio, chọn File → New Project và điền thông tin cần thiết.
Bước 2: Thiết kế giao diện (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:id="@+id/rl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
tools:context=".MainActivity">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="25sp"
android:text="Chuyển Bitmap sang Byte Array" />
<ImageView
android:id="@+id/ivSource"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_below="@id/button"
android:layout_marginTop="20dp"
android:scaleType="centerCrop"/>
<ImageView
android:id="@+id/ivCompressed"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_below="@id/button"
android:layout_marginTop="20dp"
android:layout_toRightOf="@id/ivSource"
android:scaleType="centerCrop"/>
</RelativeLayout>
Bước 3: Viết code MainActivity.java
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity {
Button button;
ImageView ivSource, ivCompressed;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
ivSource = findViewById(R.id.ivSource);
ivCompressed = findViewById(R.id.ivCompressed);
button.setOnClickListener(v -> {
try {
// Đọc ảnh từ assets
InputStream inputStream = getAssets().open("image.png");
Bitmap originalBitmap = BitmapFactory.decodeStream(inputStream);
ivSource.setImageBitmap(originalBitmap);
// Chuyển Bitmap -> byte[]
ByteArrayOutputStream stream = new ByteArrayOutputStream();
originalBitmap.compress(Bitmap.CompressFormat.JPEG, 80, stream);
byte[] byteArray = stream.toByteArray();
Toast.makeText(this,
"Kích thước byte array: " + byteArray.length + " bytes",
Toast.LENGTH_SHORT).show();
// Chuyển ngược byte[] -> Bitmap (để kiểm tra)
Bitmap compressedBitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
ivCompressed.setImageBitmap(compressedBitmap);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "Lỗi: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
Các định dạng nén:
Bitmap.CompressFormat.JPEG: Có mất dữ liệu (lossy), kích thước nhỏ, tốt cho ảnh chụpBitmap.CompressFormat.PNG: Không mất dữ liệu (lossless), kích thước lớn, tốt cho ảnh có chữ/đường nétBitmap.CompressFormat.WEBP: Cân bằng tốt (API 14+)
Utility method tái sử dụng:
public static byte[] bitmapToByteArray(Bitmap bitmap, Bitmap.CompressFormat format, int quality) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(format, quality, stream);
return stream.toByteArray();
}
public static Bitmap byteArrayToBitmap(byte[] bytes) {
return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
}
Bước 4: Cấu hình AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="app.com.sample">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Chạy ứng dụng
Đặt file image.png vào thư mục assets/. Kết nối thiết bị, nhấn Run.

