May 5, 2012

Bitmap image processing, pixel by pixel.

This example create a new bitmap from a existing bitmap with rotated color channel, Green->Blue, Red->Green, Blue->Red).

Bitmap image processing

package com.AndroidBitmapProcessing;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.ImageView;

public class AndroidBitmapProcessingActivity extends Activity {
 
 ImageView imageView_Source, imageView_Dest;
 Bitmap bitmap_Source, bitmap_Dest;
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        imageView_Source = (ImageView)findViewById(R.id.source);
        imageView_Dest = (ImageView)findViewById(R.id.dest);
        
        bitmap_Source = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
        imageView_Dest.setImageBitmap(processingBitmap(bitmap_Source));
    }
    
    private Bitmap processingBitmap(Bitmap src){
     
     Bitmap dest = Bitmap.createBitmap(
       src.getWidth(), src.getHeight(), src.getConfig());
     
     for(int x = 0; x < src.getWidth(); x++){
      for(int y = 0; y < src.getHeight(); y++){
       int pixelColor = src.getPixel(x, y);
       int pixelAlpha = Color.alpha(pixelColor);
       int pixelRed = Color.red(pixelColor);
       int pixelGreen = Color.green(pixelColor);
       int pixelBlue = Color.blue(pixelColor);
       int newPixel= Color.argb(
         pixelAlpha, pixelBlue, pixelRed, pixelGreen);
       dest.setPixel(x, y, newPixel);
      }
     }
     
     return dest;
    }
}


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
    <ImageView
        android:id="@+id/source" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:src="@drawable/ic_launcher"/>
    <ImageView
        android:id="@+id/dest" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>


No comments:

Post a Comment

Infolinks In Text Ads