এন্ড্রয়েডে বড় ইমেজ প্রসেসিং করতে গেলে অনেক সময় লাগবে। অনেক গুলো কাজই আমাদের পিক্সেল বাই পিক্সেল এ ক্যালকুলেট করতে হবে। বড় ইমেজ হলে তখন অ্যাপ স্লো হয়ে যাবে। এ জন্য আমরা যখন ইমেজ একটা ওপেন করব, তখন ইমেজটি ছোট করে নিব।
টিউটোরিয়াল সিম্পল রাখার জন্য আমরা Drawable ফোল্ডারে একটি ইমেজ রেখে কাজ করব। অ্যাপে গ্যালারি থেকে ইমেজ কিভাবে পিক করতে হয়, তা নিয়ে বিস্তারিত নিচের লেখা থেকে জানা যাবে।ঃ
একটি ইমেজ ভিউ রেখেছি। ইমেজ ভিউতে ইমেজ আউটপুট দেখাবো। আর একটি বাটন রেখেছি, যা দিয়ে আমাদের আউটপুট ইমেজটি সেভ করতে পারব।
activity_main.xml ফাইলটিঃ
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button android:text="Save Image"
android:id="@+id/save"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
<ImageView
android:id="@+id/imageView"
android:src="@drawable/ic_launcher"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ImageView>
</LinearLayout>
জাভা কোড, বিস্তারিত নিচেঃ
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity {
private Bitmap bitmap;
private ImageView imageView;
Button save;
Drawable myImage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
// read image from Drawable
myImage = ContextCompat.getDrawable(this, R.drawable.jack);
bitmap = ((BitmapDrawable) myImage).getBitmap();
// calculate aspect ratio
float aspectRatio = bitmap.getWidth() /
(float) bitmap.getHeight();
int width = 600;
int height = Math.round(width / aspectRatio);
// resizing
bitmap = Bitmap.createScaledBitmap(bitmap, width, height, false);
imageView.setImageBitmap(bitmap);
// saving to gallery
save = (Button)findViewById(R.id.save);
save.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "New image name", "Image description");
}
});
}
}
আমরা একটি বিটম্যাপ ইমেজকে রিসাইজ করছি। তার জন্য কোড হচ্ছে Bitmap.createScaledBitmap(bitmap, width, height, false); এখানে width এবং height এ 200 এবং 200 দিলে ইমেজটি রিসাইজ হয়ে 200*200 পিক্সেলের একটি ইমেজ হয়ে যাবে।
আমরা যে ইমেজ ওপেন করব, তা রিসাইজ করতে হলে তার aspect ratio ঠিক রাখতে হবে। aspect ratio হচ্ছে ইমেজের width এবং height এর রেশিও। আমাদের অ্যাপে ইমেজের ওয়াইড ঠিক করে দিয়েছি 600, aspect ratio ঠিক রেখে height হিসেব করে নিয়েছি। এবং শেষে ইমেজ ভিউতে লোড করেছি। এই!