Sunday, December 3, 2017

How to encode images into a video file in Java through programming?

Using command line, there are various ways to convert an image to video. You can use those command in java for saving. You can get those commands from the following link:
  1. Using ffmpeg to convert a set of images into a video
  2. Create a video slideshow from images

I am sharing a code snippet to solve the issue:

code to save png image from HTML5 canvas
Base64 decoder = new Base64();
byte[] pic = decoder.decodeBase64(request.getParameter("pic"));
String frameCount = request.getParameter("frame");
InputStream in = new ByteArrayInputStream(pic);
BufferedImage bImageFromConvert = ImageIO.read(in);
String outdir = "output\\"+frameCount;
//Random rand = new Random();
File file = new File(outdir);
if(file.isFile()){
    if(file.delete()){
        File writefile = new File(outdir);
        ImageIO.write(bImageFromConvert, "png", file);
    }
}
Code for creating image from video
String filePath = "D:\\temp\\some.mpg";
String outdir = "output";
File file = new File(outdir);
file.mkdirs();
Map<String, String> m = System.getenv();

/*
 * String command[] =
 * {"D:\\ffmpeg-win32-static\\bin\\ffmpeg","-i",filePath
 * ,"-r 30","-f","image2",outdir,"\\user%03d.jpg"};
 * 
 * ProcessBuilder pb = new ProcessBuilder(command); pb.start();
 */
String commands = "D:\\ffmpeg-win32-static\\bin\\ffmpeg -i " + filePath
        + " -r 30  -f image2 " + outdir + "\\image%5d.png";
Process p = Runtime.getRuntime().exec(commands);
code for creating video from image
String filePath = "output";
File fileP = new File(filePath);
String commands = "D:\\ffmpeg-win32-static\\bin\\ffmpeg -f image2 -i "
        + fileP + "\\image%5d.png " + fileP + "\\video.mp4";
System.out.println(commands);
Runtime.getRuntime().exec(commands);
System.out.println(fileP.getAbsolutePath());
Credit goes to @yashprit

Another approach for Android developers:

  1. Create a temporary folder inside the Android.
  2. Copy your images in the new folder
  3. First, rename your pictures to follow a numerical sequence. For example, img1.jpg, img2.jpg, img3.jpg,... Then you may run:
  4. Run this program programmatically ffmpeg -f image2 -i img%d.jpg /tmp/a.mpg To run this programmatically,
Use the following code:
void convertImg_to_vid()
{
    Process chperm;
    try {
        chperm=Runtime.getRuntime().exec("su");
          DataOutputStream os = 
              new DataOutputStream(chperm.getOutputStream());

              os.writeBytes("ffmpeg -f image2 -i img%d.jpg /tmp/a.mpg\n");
              os.flush();

              chperm.waitFor();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

Resource Link:

  1. Create a Video file from images using ffmpeg

No comments:

Post a Comment