Saturday, August 3, 2019

combineImages





Combine two images and draw new Image Java Code.



import java.io.File;
import java.awt.Color;
import java.awt.Graphics2D;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;


public class Main {
   
public static void main(String args[]) throws Exception {
        BufferedImage img1 = ImageIO.read(
new File("1.jpg"));
        BufferedImage img2 = ImageIO.read(
new File("2.jpg"));
        BufferedImage joinedImg = combineImage(img1, img2);
        ImageIO.write(joinedImg,
"png", new File("combined.png"));
    }







public static BufferedImage combineImage(BufferedImage img1, BufferedImage img2) {
       
int offset = 2;
       
int width = Math.min(img1.getWidth(), img2.getWidth()) + offset;
       
int height = img1.getHeight()+ img2.getHeight() +offset;
        BufferedImage outImage =
new BufferedImage(width, height,
                BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2D = newImage.createGraphics();
        Color imgColor = g2D.getColor();
        g2D.setPaint(Color.BLACK);
        g2D.fillRect(
0, 0, width, height);
        g2D.setColor(imgColor);
        g2D.drawImage(img1,
null, 0, 0);
        g2D.drawImage(img2,
null,0,img1.getHeight()+offset);
        g2D.dispose();
       
return outImage;
    }
}





**************************************************


Combine two images and draw new Image Android Code.


public void combineImage(Context context) {
   
int offset = 2;
    File sdcard = Environment.getExternalStorageDirectory();
   
    File dir =
new File(sdcard.getAbsolutePath() + "/path/");
    Bitmap topImage = BitmapFactory.decodeFile(dir +
"/img1.JPG");
    Bitmap bottomImage = BitmapFactory.decodeFile(dir +
"/img2.JPG");
   
   
int width = Math.min(topImage.getWidth(), bottomImage.getWidth()) + offset;
   
int height = topImage.getHeight() + bottomImage.getHeight() + offset;
   
    Bitmap mutableBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.
ARGB_8888);

    Canvas comboImage =
new Canvas(mutableBitmap);

    Paint paint =
new Paint();

    comboImage.drawBitmap(topImage,
0, 0, paint);
    comboImage.drawBitmap(bottomImage,
0, topImage.getHeight(), paint);
   
    OutputStream os =
null;
   
try {
        os =
new FileOutputStream(new File(dir, "output.JPG"));
        mutableBitmap.compress(Bitmap.CompressFormat.
JPEG, 50, os);
        os.flush();
        os.close();
    }
catch (Exception e) {
        e.printStackTrace();
    }
}

1 comment:

Home

Mastering Java Interview Questions: Your Comprehensive Guide         If you're preparing for a Java interview or just lookin...