Pour afficher un Bitmap :
Par exemple pour une icône de 64×64 pixels :
a) Créer un Layout avec une image view :
<ImageView
android:id="@+id/imgView"
android:layout_width="64dp"
android:layout_height="64dp">
</ImageView>
b) Remplissage de l’image view avec le Bitmap :
setContentView(R.layout.activity_main);
ImageView profile = (ImageView) findViewById(R.id.imgView);
profile.setImageBitmap(ficbitmap);
Pour convertir un Drawable en Bitmap :
Utilisez la fonction DecodeBitmap :
BitmapFactory.decodeResource(getResources(), R.drawable.<nom_du_drawable>);
exemple :
profile.setImageBitmap(BitmapFactory.decodeResource( getResources(), R.drawable.horse));
Pour redimensionner une image Bitmap :
Bitmap ImageFromGal = BitmapFactory
.decodeFile(imgDecodableString);
ImageFromGal = Bitmap.createScaledBitmap(
ImageFromGal, 64, 64, false);
Pour obtenir des images à partir de la gallerie du smartphone :
attention inclure dans le manifest la permissions :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
public void loadImagefromGallery(View view) {
// Create intent to Open Image applications like Gallery, Google Photos
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
// When an Image is picked
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data)
{
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
ImageView imgView = (ImageView) findViewById(R.id.imgView);
//-- Resize Image to 64x64
Bitmap ImageFromGal = BitmapFactory
.decodeFile(imgDecodableString);
ImageFromGal = Bitmap.createScaledBitmap(
ImageFromGal, 64, 64, false);
bFic = UtilityImg.getBytes(ImageFromGal);
DbHelper.updateContact(dbContact, bFic);
//-- Set Image in Image View
imgView.setImageBitmap(ImageFromGal);
} finally {
if (cursor != null) {
cursor.close();
}
}
} else
{
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Can't load picture...", Toast.LENGTH_LONG)
.show();
}
}
Pour obtenir des images à partir des contacts du répertoire :
Inclure dans le manifest la permission :
<uses-permission android:name="android.permission.READ_CONTACTS" />
public void loadImagefromContact(View view) {
//-- On recherche le contact
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(intent, RESULT_LOAD_CONTACT);
}
if (requestCode == RESULT_LOAD_CONTACT && resultCode == RESULT_OK
&& null != data) { ///
Uri uri = data.getData();
if (uri != null) {
Cursor cursor = null;
try {
cursor = getContentResolver().query(uri, new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER},
null, null, null);
String phoneNumber = null, contactId = null;
if (cursor != null && cursor.moveToFirst()) {
contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
phoneNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//phoneNorm = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER));
///
ImageView profile = (ImageView) findViewById(R.id.imgView);
Uri my_contact_Uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, String.valueOf(contactId));
InputStream photo_stream = ContactsContract.Contacts.openContactPhotoInputStream(getContentResolver(), my_contact_Uri);
BufferedInputStream buf = new BufferedInputStream(photo_stream);
if (photo_stream!=null){
Bitmap my_btmp = BitmapFactory.decodeStream(buf);
bFic=UtilityImg.getBytes(my_btmp);
DbHelper.updateContact(dbContact, bFic);
profile.setImageBitmap(my_btmp);
try {
buf.close();
} catch (IOException e) {
e.printStackTrace();
}}}}}}
Pour stocker des images dans une base de données :
Pour gérer la base de données, créez une classe « DbHelper » :
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DbHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "dbimg.db";
private static final int DATABASE_VERSION = 1;
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
//-- Table contact contient les raccourcis
db.execSQL(
"CREATE TABLE IF NOT EXISTS contact ( " +
"ficico blob," +
"idico integer)");
}
public static long CompteContact(SQLiteDatabase db) {
Log.d("Base", "Nb enr=" + String.valueOf(DatabaseUtils.queryNumEntries(db, "contact")));
return DatabaseUtils.queryNumEntries(db, "contact");
}
public static int updateContact(SQLiteDatabase db, byte[] FicIco) {
ContentValues values = new ContentValues();
values.put("ficico", FicIco);
return db.update("contact", values, "idico = 1" , null);
}
public static byte[] litImageContact(SQLiteDatabase db) {
byte[] byteImage=null;
Cursor cursor = db.query("contact", null,
"idico = 1", null, null, null, null);
if (cursor.moveToFirst()) {
do {
byteImage = cursor.getBlob(0);
} while (cursor.moveToNext());
}
return byteImage;
}
public static long insertContact(SQLiteDatabase db, byte[] FicIco) {
ContentValues values = new ContentValues();
values.put("idico", 1);
values.put("ficico", FicIco);
return db.insert("contact", null, values);
}
//////////////////////
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion >= newVersion)
return;
if (oldVersion == 1) {
Log.d("New Version", "Datas can be upgraded");
}
Log.d("Sample Data", "onUpgrade : " + newVersion);
}
}
L’utilisation étant :
On défini un tableau de bytes qui va stocker l’image : private byte[] bFic=null;
Stockage :
bFic=UtilityImg.getBytes(BitmapFactory.decodeResource(getResources(), R.drawable.horse));
DbHelper.insertContact(dbContact,bFic);
Restitution :
bFic=DbHelper.litImageContact(dbContact);
Pour convertir le tableau de bytes on utilise la fonction getPhoto (décrite en bas de page) :
profile.setImageBitmap(UtilityImg.getPhoto(bFic));
Les trois dernières fonctionnalités énoncées ont besoin des fonctions :
// convert from bitmap to byte array
public static byte[] getBytes(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, stream);
return stream.toByteArray();
}
// convert from byte array to bitmap
public static Bitmap getPhoto(byte[] image) {
return BitmapFactory.decodeByteArray(image, 0, image.length);
}
}
Références :
Un exemple de mise en oeuvre est ici