001package com.github.sarxos.webcam; 002 003import java.io.File; 004import java.io.IOException; 005import java.nio.ByteBuffer; 006import java.util.Locale; 007import java.util.PropertyResourceBundle; 008import java.util.ResourceBundle; 009 010import javax.imageio.ImageIO; 011 012import com.github.sarxos.webcam.util.ImageUtils; 013 014 015public class WebcamUtils { 016 017 public static final void capture(Webcam webcam, File file) { 018 if (!webcam.isOpen()) { 019 webcam.open(); 020 } 021 try { 022 ImageIO.write(webcam.getImage(), ImageUtils.FORMAT_JPG, file); 023 } catch (IOException e) { 024 throw new WebcamException(e); 025 } 026 } 027 028 public static final void capture(Webcam webcam, File file, String format) { 029 if (!webcam.isOpen()) { 030 webcam.open(); 031 } 032 try { 033 ImageIO.write(webcam.getImage(), format, file); 034 } catch (IOException e) { 035 throw new WebcamException(e); 036 } 037 } 038 039 public static final void capture(Webcam webcam, String filename) { 040 if (filename.endsWith(".jpg")) { 041 filename = filename + ".jpg"; 042 } 043 capture(webcam, new File(filename)); 044 } 045 046 public static final void capture(Webcam webcam, String filename, String format) { 047 String ext = "." + format.toLowerCase(); 048 if (!filename.startsWith(ext)) { 049 filename = filename + ext; 050 } 051 capture(webcam, new File(filename), format); 052 } 053 054 public static final byte[] getImageBytes(Webcam webcam, String format) { 055 return ImageUtils.toByteArray(webcam.getImage(), format); 056 } 057 058 /** 059 * Capture image as BYteBuffer. 060 * 061 * @param webcam the webcam from which image should be obtained 062 * @param format the file format 063 * @return Byte buffer 064 */ 065 public static final ByteBuffer getImageByteBuffer(Webcam webcam, String format) { 066 return ByteBuffer.wrap(getImageBytes(webcam, format)); 067 } 068 069 /** 070 * Get resource bundle for specific class. 071 * 072 * @param clazz the class for which resource bundle should be found 073 * @return Resource bundle 074 */ 075 public static final ResourceBundle loadRB(Class<?> clazz, Locale locale) { 076 String pkg = WebcamUtils.class.getPackage().getName().replaceAll("\\.", "/"); 077 return PropertyResourceBundle.getBundle(String.format("%s/i18n/%s", pkg, clazz.getSimpleName())); 078 } 079}