Image Resize di Java

Di Java ME terkadang penggunaan image menjadi masalah, ukuran screen dari display yang berbeda-beda. Ada kalanya kita perlu untuk melakukan manipulasi pada gambar, di sini gw bakal kasih satu method simple untuk melakukan resize image.
  1. public static Image resizeImage(Image src, int newWidth, int newHeight) {  
  2.   
  3.      int srcWidth = src.getWidth();  
  4.      int srcHeight = src.getHeight();  
  5.   
  6.      Image tmp = Image.createImage(newWidth, srcHeight);  
  7.      Graphics g = tmp.getGraphics();  
  8.      int ratio = (srcWidth << 16) / newWidth;  
  9.      int pos = ratio/2;  
  10.   
  11.      //Horizontal Resize  
  12.      for (int x = 0; x < newWidth; x++) {  
  13.          g.setClip(x, 01, srcHeight);  
  14.          g.drawImage(src, x - (pos >> 16), 0, Graphics.LEFT | Graphics.TOP);  
  15.          pos += ratio;  
  16.      }  
  17.   
  18.      Image resizedImage = Image.createImage(newWidth, newHeight);  
  19.      g = resizedImage.getGraphics();  
  20.      ratio = (srcHeight << 16) / newHeight;  
  21.      pos = ratio/2;  
  22.   
  23.      //Vertical resize  
  24.      for (int y = 0; y < newHeight; y++) {  
  25.         g.setClip(0, y, newWidth, 1);  
  26.         g.drawImage(tmp, 0, y - (pos >> 16), Graphics.LEFT | Graphics.TOP);  
  27.         pos += ratio;  
  28.      }  
  29.   
  30.      return resizedImage;  
  31. }  

Post a Comment