Creating video from a group of images in java

I had to build a facebook app where I would combine all the best photos of the user and create a video out of it. After searching a lot I found a solution for Java. So xuggler is a java library which helps in creating videos from images. Xuggler can be downloaded here

Here is the code for it :

                JsonObject jsonObject = null;//Assuming you have this json object which contains URLs of the images which needs to be downloaded and                          //added to video
		int width = 700;
		int height = 400;
		int rn = new Random().nextInt(1000000);
		final IMediaWriter videowriter = ToolFactory.makeWriter(PATH +  ".mp4");
		videowriter
				.addVideoStream(0, 0, ICodec.ID.CODEC_ID_H264, width, height);
 
		int seconds = 0;
		JsonArray array = jsonObject.getJsonArray("data");
		for (int x = 0; x < array.length(); x++) {
			try {
				JsonObject jobj = array.getJsonObject(x);
				if (!jobj.has("url"))
					continue;
				String url = jobj.getString("url");// URL of the image
				int delay = jobj.getInt("delay"); // Delay between previous frame and current frame
				BufferedImage srcimg = ImageIO.read(new URL(url));
				BufferedImage finalImg = new BufferedImage(width, height, 5);
				Image img = srcimg.getScaledInstance(width, height, Image.SCALE_SMOOTH);
				finalImg.createGraphics().drawImage(img, 0, 0, null);
				videowriter.encodeVideo(0, finalImg, seconds, TimeUnit.SECONDS);
				seconds += delay;
			} catch (Exception e) {
				e.printStackTrace();
			}
 
		}
 
		videowriter.close();

So this code expects a json object which contains URLs of images which needs to be downloaded and converted into video. You can also provide the delay between the frames. It creates a videoWriter object using xuggler’s api. Then it defines the codec and height/width of the video. Then we iterate over the image URLs, download them and add them to the video. In the end we need to close the writer object to release resources it would have held

Uday Ogra

Connect with me at http://facebook.com/tendulkarogra and lets have some healthy discussion :)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *