Showing posts with label ImageView. Show all posts
Showing posts with label ImageView. Show all posts

Friday, March 23, 2012

How to detect Gesture based action in Android?


I have list of images in a listview with url. When the user wants view the full image then user click the image on the list view
it will take to me the anonther activity and open in a imageview. and as a user wants to tee the next nexe or previous image with come back to listview page

Solution : I have created the HashMap Contains the list of images and pass the selected images name as bundle string. In a detail view created the async task the fetch image from the internet
implement the gestureListener. In this article we discussing about that

Related : gesture move action, gesture based action, example geatures

1. Create a Activity implements OnClickListener
public class MySample1Activity extends Activity implements OnClickListener {
........
}
2. Initialize below required object for gestureListener
ViewConfiguration vc;

static int SWIPE_MAX_OFF_PATH = 250;
static int SWIPE_MIN_DISTANCE = 100;
static int SWIPE_THRESHOLD_VELOCITY = 100;

private GestureDetector gestureDetector;
View.OnTouchListener gestureListener;

3. Set Densitybased velocity
vc = ViewConfiguration.get(this);
SWIPE_MIN_DISTANCE = vc.getScaledTouchSlop();
SWIPE_THRESHOLD_VELOCITY = vc.getScaledMinimumFlingVelocity();

4. Create a Custom GestureListener class which extends SimpleOnGestureListener
class MyGestureDetector extends SimpleOnGestureListener {

}

5. Override the onFling() and implement the geature move action
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
try {
if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
return false;
// right to left swipe
if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
Toast.makeText(MySample1Activity.this, "Left Swipe",
Toast.LENGTH_SHORT).show();
} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
Toast.makeText(MySample1Activity.this, "Right Swipe",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// nothing
}
return false;
}

Full SourceCode
public class MySample1Activity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
TextView tView;

ViewConfiguration vc;

static int SWIPE_MAX_OFF_PATH = 250;
static int SWIPE_MIN_DISTANCE = 100;
static int SWIPE_THRESHOLD_VELOCITY = 100;

private GestureDetector gestureDetector;
View.OnTouchListener gestureListener;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tView = (TextView) findViewById(R.id.textview1);
vc = ViewConfiguration.get(this);
SWIPE_MIN_DISTANCE = vc.getScaledTouchSlop();
SWIPE_THRESHOLD_VELOCITY = vc.getScaledMinimumFlingVelocity();

gestureDetector = new GestureDetector(new MyGestureDetector());
gestureListener = new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (gestureDetector.onTouchEvent(event)) {
return true;
}
return false;
}
};
tView.setOnClickListener(this);
tView.setOnTouchListener(gestureListener);
}

class MyGestureDetector extends SimpleOnGestureListener {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
try {
if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
return false;
// right to left swipe
if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
Toast.makeText(MySample1Activity.this, "Left Swipe",
Toast.LENGTH_SHORT).show();
} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
Toast.makeText(MySample1Activity.this, "Right Swipe",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// nothing
}
return false;
}
}

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

}

}


Combining 2 Images in Android using Canvas ?


Below are the methods to canvert the two bitmap in to one..........


 private BitmapDrawable createUserMarker(Bitmap bmp1, Bitmap bmp2) {
Bitmap bitmapStar = bmp1;
Bitmap bmOverlay = Bitmap.createBitmap(bmp2.getWidth(), bmp2.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bmOverlay);
canvas.drawARGB(0x00, 0, 0, 0);
canvas.drawBitmap(bmp2, 0, 0, null);
canvas.drawBitmap(bitmapStar, 2, 2, null);
BitmapDrawable dr = new BitmapDrawable(bmOverlay);
dr.setBounds(0, 0, dr.getIntrinsicWidth(), dr.getIntrinsicHeight());
return (dr);
    }


OR


 public Bitmap combineImages(Bitmap c, Bitmap s) { 
// can add a 3rd parameter 'String loc' if you want to save the new
// image - left some code to do that at the bottom 
   Bitmap cs = null; 
 
   int width, height = 0; 
    
   if(c.getWidth() > s.getWidth()) { 
     width = c.getWidth(); 
     height = c.getHeight() + s.getHeight(); 
   } else { 
     width = s.getWidth(); 
     height = c.getHeight() + s.getHeight(); 
   } 
 
   cs = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); 
 
   Canvas comboImage = new Canvas(cs); 
 
   comboImage.drawBitmap(c, 0f, 0f, null); 
   comboImage.drawBitmap(s, 0f, c.getHeight(), null); 
 
   // this is an extra bit I added, just incase you want to save the new image somewhere and then return the location 
   /*String tmpImg = String.valueOf(System.currentTimeMillis()) + ".png"; 
 
   OutputStream os = null; 
   try { 
     os = new FileOutputStream(loc + tmpImg); 
     cs.compress(CompressFormat.PNG, 100, os); 
   } catch(IOException e) { 
     Log.e("combineImages", "problem combining images", e); 
   }*/ 
 
   return cs; 
 } 




Tuesday, March 20, 2012

How to Attach EXIF metadata to a serialized Bitmap in Android?


After uploading image to server from Android mobile, I also needed exif information of the image. EXIF information are metadata about image file. It contains information like, Camera name, date taken, Longitude and latitude etc.
After 2.0 SDK of Android, we have exifinterface available to read exif information of the file stored in SD card.
I read a file and get Bitmap object and then I compress it to get byte array. But while compressing it, I loose this information. Thanks to Sanselan, Apache project, By adding this library, I am now able to add exif information to byte array.

ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, bos); //Bitmap object is your image
byte[] data = bos.toByteArray();

TiffOutputSet outputSet = null;

IImageMetadata metadata = Sanselan.getMetadata(new File(filepath)); // filepath is the path to your image file stored in SD card (which contains exif info)
JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata;
if (null != jpegMetadata)
{
    TiffImageMetadata exif = jpegMetadata.getExif();
    if (null != exif)
    {
        outputSet = exif.getOutputSet();
    }
}
if (null != outputSet)
{
    bos.flush();
    bos.close();
    bos = new ByteArrayOutputStream();
    ExifRewriter ER = new ExifRewriter();
    ER.updateExifMetadataLossless(data, bos, outputSet);
    data = bos.toByteArray(); //Update you Byte array, Now it contains exif information!
}

Friday, February 10, 2012

How to create an image with reflexion in android?

This takes an existing bitmap and adds a reflection to the bottom. 
 public static Bitmap createReflectedImage(Context context, Bitmap originalImage) {
  //The gap we want between the reflection and the original image
  final int reflectionGap = 4;
  
  int width = originalImage.getWidth();
  int height = originalImage.getHeight();
  
 
  //This will not scale but will flip on the Y axis
  Matrix matrix = new Matrix();
  matrix.preScale(1, -1);
  
  //Create a Bitmap with the flip matrix applied to it.
  //We only want the bottom half of the image
  Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0, height/2, width, height/2, matrix, false);
  
   
  //Create a new bitmap with same width but taller to fit reflection
  Bitmap bitmapWithReflection = Bitmap.createBitmap(width
  , (height + height/2), Config.ARGB_8888);
  
  //Create a new Canvas with the bitmap that's big enough for
  //the image plus gap plus reflection
  Canvas canvas = new Canvas(bitmapWithReflection);
  //Draw in the original image
  canvas.drawBitmap(originalImage, 0, 0, null);
  //Draw in the gap
  Paint defaultPaint = new Paint();
  canvas.drawRect(0, height, width, height + reflectionGap, defaultPaint);
  //Draw in the reflection
  canvas.drawBitmap(reflectionImage,0, height + reflectionGap, null);
  
  //Create a shader that is a linear gradient that covers the reflection
  Paint paint = new Paint();
  LinearGradient shader = new LinearGradient(0, originalImage.getHeight(), 0,
  bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff, 0x00ffffff,
  TileMode.CLAMP);
  //Set the paint to use this shader (linear gradient)
  paint.setShader(shader);
  //Set the Transfer mode to be porter duff and destination in
  paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
  //Draw a rectangle using the paint with our linear gradient
  canvas.drawRect(0, height, width,
  bitmapWithReflection.getHeight() + reflectionGap, paint);
  
  return bitmapWithReflection;
 }

How to load a remote image from the web in Android?

Load a remote image from the web and return it as Bitmap. 
public Bitmap getRemoteImage(final URL aURL) {
    try {
        final URLConnection conn = aURL.openConnection();
        conn.connect();
        final BufferedInputStream bis = new BufferedInputStream(
  conn.getInputStream());
        final Bitmap bm = BitmapFactory.decodeStream(bis);
        bis.close();
        return bm;
    } catch (IOException e) {
        Log.d("DEBUGTAG", "Oh noooz an error...");
    }
    return null;
}

Sunday, February 5, 2012

How to make a bitmap corner curved?


Send the bitmap image,and also pixel amount to curve image.........in below method

public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
final float roundPx = pixels;
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;

    }

Monday, January 30, 2012

Loading a image from sdcard in different ways?



Android - Load a image in a file (not drawable) as image in the layout

Sometimes, it is easier load a image from other directory (sdcard, for example) 
than load a image from drawable because for this last case, the image should be
 stored in the directory res/drawable first and packaged along with the apk files.

To load a image from a directory, it should be converted to the drawable first. 
Here comes a piece of code which can help:

File file = new File ("/sdcard/1.jpg");
ImageView imageView = (ImageView) findViewById(R.id.icon);
imageView.setImageDrawable(Drawable.createFromPath(file.getAbsolutePath()));

Be warning that there is another method for ImageView called setImageURI(URI uri).
 This method is used to load external files, it doesn't work with the type file.
 For example, this code won't work:


File file = new File ("/sdcard/1.jpg");
ImageView imageView = (ImageView) findViewById(R.id.icon);
imageView.setImageURI(Uri.fromFile(file));
--------------------------------------------------------------------------------------------------------------------------------
The another way to use image from sdcard you can write the following code...........


imagePath="/sdcard"+"/"+filename;
try {
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
imageview.setImageBitmap(bitmap);

} catch (Exception e) {
e.printStackTrace();
File photos= new File("/sdcard/", "/Wockhardt/"+selectedFolderName+"/"+filename);
Bitmap b = decodeFile(photos);
imageview.setImageBitmap(b);



private Bitmap decodeFile(File f){
        try {
            //decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f),null,o);


            //Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE=70;
            int width_tmp=o.outWidth, height_tmp=o.outHeight;
            int scale=1;
            while(true){
                if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
                    break;
                width_tmp/=2;
                height_tmp/=2;
                scale++;
            }


            //decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize=scale;
            return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
        } catch (FileNotFoundException e) {}
        return null;
    }