I am trying to implement some ocr using a guide from on stackoverflow. the example code for the use of the application is using java and i am trying to run it on android. Here is the code from the example;
// OCRScannerDemo.java
// Copyright (c) 2003-2009 Ronald B. Cemer
// All rights reserved.
/*
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.roncemer.ocr.main;
import java.awt.Frame;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.ScrollPane;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.ImageProducer;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import com.roncemer.ocr.CharacterRange;
import com.roncemer.ocr.OCRImageCanvas;
import com.roncemer.ocr.OCRScanner;
import com.roncemer.ocr.PixelImage;
import com.roncemer.ocr.TrainingImageLoader;
import com.roncemer.ocr.tracker.MediaTrackerProxy;
/**
* Demo application to demonstrate OCR document scanning and decoding.
* #author Ronald B. Cemer
*/
public class OCRScannerDemo extends Frame {
private static final long serialVersionUID = -8030499184564680363L;
private boolean debug = true;
private Image image;
private OCRImageCanvas imageCanvas;
private OCRScanner scanner;
public OCRScannerDemo() {
super("OCR from a scanned image");
setSize(1024, 768);
ScrollPane scrollPane = new ScrollPane();
imageCanvas = new OCRImageCanvas();
scrollPane.add(imageCanvas);
add(scrollPane);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
((Frame)(e.getSource())).hide();
System.exit(0);
}
});
scanner = new OCRScanner();
show();
}
/**
* Load demo training images.
* #param trainingImageDir The directory from which to load the images.
*/
public void loadTrainingImages(String trainingImageDir) {
if (debug) System.err.println("loadTrainingImages(" + trainingImageDir + ")");
if (!trainingImageDir.endsWith(File.separator)) {
trainingImageDir += File.separator;
}
try {
scanner.clearTrainingImages();
TrainingImageLoader loader = new TrainingImageLoader();
HashMap images = new HashMap();
if (debug) System.err.println("ascii.png");
loader.load(
this,
trainingImageDir + "ascii.png",
new CharacterRange('!', '~'),
images);
if (debug) System.err.println("hpljPica.jpg");
loader.load(
this,
trainingImageDir + "hpljPica.jpg",
new CharacterRange('!', '~'),
images);
if (debug) System.err.println("digits.jpg");
loader.load(
this,
trainingImageDir + "digits.jpg",
new CharacterRange('0', '9'),
images);
if (debug) System.err.println("adding images");
scanner.addTrainingImages(images);
if (debug) System.err.println("loadTrainingImages() done");
}
catch(IOException ex) {
ex.printStackTrace();
System.exit(2);
}
}
public void process(String imageFilename) {
if (debug) System.err.println("process(" + imageFilename + ")");
String imageFileUrlString = "";
try {
imageFileUrlString = new File(imageFilename).toURL().toString();
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
ImageProducer imageProducer = (ImageProducer)
(new URL(imageFileUrlString).getContent());
image = createImage(imageProducer);
}
catch(IOException e) {
e.printStackTrace();
}
if (image == null) {
System.err.println("Cannot find image file at " + imageFileUrlString);
return;
}
MediaTracker mt = new MediaTrackerProxy(this);
mt.addImage(image, 0);
try {
mt.waitForAll();
} catch(InterruptedException ex) {}
if (debug) System.err.println("image loaded");
/* int w = image.getWidth(null);
int h = image.getHeight(null);
if ( (w > 0) && (h > 0) ) {
float scaleFactor = 2048.0f/(float)Math.max(w, h);
if (scaleFactor < 1.0f) {
image = image.getScaledInstance(
(int)((float)w*scaleFactor),
(int)((float)h*scaleFactor), Image.SCALE_SMOOTH);
mt = new MediaTrackerProxy(this);
mt.addImage(image, 0);
try { mt.waitForAll(); } catch(InterruptedException ex) {}
}
}*/
imageCanvas.setSize(image.getWidth(null), image.getHeight(null));
if (debug) System.err.println("constructing new PixelImage");
PixelImage pixelImage = new PixelImage(image);
if (debug) System.err.println("converting PixelImage to grayScale");
pixelImage.toGrayScale(true);
if (debug) System.err.println("filtering");
pixelImage.filter();
if (debug) System.err.println("setting image for display");
imageCanvas.setImage(
pixelImage.rgbToImage(
pixelImage.grayScaleToRGB(pixelImage.pixels),
pixelImage.width,
pixelImage.height,
imageCanvas));
System.out.println(imageFilename + ":");
String text = scanner.scan(image, 0, 0, 0, 0, null, imageCanvas.getGraphics());
System.out.println("[" + text + "]");
}
public static void main(String[]args) {
if (args.length < 1) {
System.err.println("Please specify one or more image filenames.");
System.exit(1);
}
String trainingImageDir = System.getProperty("TRAINING_IMAGE_DIR");
if (trainingImageDir == null) {
System.err.println
("Please specify -DTRAINING_IMAGE_DIR=<dir> on " +
"the java command line.");
return;
}
OCRScannerDemo demo = new OCRScannerDemo();
demo.loadTrainingImages(trainingImageDir);
for (int i = 0; i < args.length; i++)
demo.process(args[i]);
System.out.println("done.");
}
}
In the process method an ImageProducer is used. Is there an alternative for android or had i might as well give up using this approach?
Kind regards
A bit late reply, but I guess it may help readers.
On Android, consider the android.graphics.Bitmap class as entry point for building images.
It is a straight forward simplification about creating and using images, when compared to Java AWT API. Android's Bitmap class resembles a lot the java.awt.BufferedImage, one with set/getPixel methdos and another one with set/getRGB, as well some methods to create bitmaps (images) from different sources.
Related
I have a Java applet (developed in NetBeans 7.4 and using JMF) for taking pictures from a web camera, it initializes the webcam automatically at startup (by using JMF)...
(APPLET)
For making it run it's necessary to add the jmf.properties file inside same directory of JAR file like this:
I tried to show this component inside a HTML page for taking snapshots from a WebBrowser but the JMF doesn't work there, everytime I run it I get this message (trying to initialize the webCam with JMF):
then it just displays the applet
this is my HTML code (Generated by Netbeans)
<HTML>
<HEAD>
<TITLE>Applet HTML Page</TITLE>
</HEAD>
<BODY>
<!--
*** GENERATED applet HTML launcher - DO NOT EDIT IN 'BUILD' FOLDER ***
If you need to modify this HTML launcher file (e.g., to add applet parameters),
copy it to where your applet class is found in the SRC folder. If you do this,
the IDE will use it when you run or debug the applet.
Tip: To exclude an HTML launcher from the JAR file, use exclusion filters in
the Packaging page in the Project Properties dialog.
For more information see the online help.
-->
<H3><HR WIDTH="100%">Applet HTML Page<HR WIDTH="100%"></H3>
<P>
<APPLET codebase="classes" code="com/xxx/pantallas/CamaraApplet.class" width=350 height=200></APPLET>
</P>
<HR WIDTH="100%"><FONT SIZE=-1><I>Generated by NetBeans IDE</I></FONT>
</BODY>
</HTML>
and the directory from where I open my HTML
Any help for making the webCam running from the HTML as well I'll appreciate
Requirements:
Have installed JDK 32Bit version
Have installed JMF: Link to download page
Full project: Link to download page
**Libraries required***** : Link to download page
***libraries are required for using JMF on the project
For make this project running I use:
2 classes
1 applet (main)
1 HTML file
CameraApplet.java (Applet)
import java.lang.reflect.InvocationTargetException;
import javax.media.Player;
import javax.swing.JPanel;
import static com.sun.java.accessibility.util.AWTEventMonitor.addWindowListener;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class CameraApplet extends javax.swing.JApplet {
private Player p1;
public Player getPlayer() {return p1;}
public void setPlayer(Player pin) {p1 = pin;}
public JPanel getCamera() {return panelCam;}
private void initComponents2() {
//Register all the listeners of the Events
AuxClass e = new AuxClass(this);
addWindowListener(e);
jmCArchivo.addActionListener(e);
//Loads in menu all detected devices
AuxClass.DevicesMenuApplet(this, jmDispositivos);
//applet size
setSize(680, 840);
//Autostarts camera
AuxClass.setCameraApplet(CameraApplet.this,
AuxClass.detectAvailableWebCameras().get(0),
0);
}
#Override
public void init() {
//Establecer los valores de look and feel del applet
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch(ClassNotFoundException | IllegalAccessException | InstantiationException | UnsupportedLookAndFeelException e){
AuxClass.showErrorMessage(null, "Ocurrio un error: " + e.toString());
}
/* crea y muestra el applet */
try {
java.awt.EventQueue.invokeAndWait(new Runnable() {
public void run() {
initComponents();
initComponents2();
}
});
}
catch (InterruptedException | InvocationTargetException e){
AuxClass.showErrorMessage(null, "Ocurrio un error: " + e.toString());
}
}
/**
* This method is called from within the init() method to initialize the
* form. WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
panelCam = new javax.swing.JPanel();
jMenuBar1 = new javax.swing.JMenuBar();
jmCapturar = new javax.swing.JMenu();
jmCArchivo = new javax.swing.JMenuItem();
jmDispositivos = new javax.swing.JMenu();
setPreferredSize(new java.awt.Dimension(640, 480));
panelCam.setBorder(javax.swing.BorderFactory.createTitledBorder("Camara Web"));
panelCam.setPreferredSize(new java.awt.Dimension(640, 480));
panelCam.setLayout(new java.awt.BorderLayout());
jmCapturar.setText("Capturar");
jmCArchivo.setText("En Archivo");
jmCapturar.add(jmCArchivo);
jMenuBar1.add(jmCapturar);
jmDispositivos.setText("Dispositivos");
jMenuBar1.add(jmDispositivos);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(panelCam, javax.swing.GroupLayout.DEFAULT_SIZE, 442, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(panelCam, javax.swing.GroupLayout.DEFAULT_SIZE, 358, Short.MAX_VALUE)
.addContainerGap())
);
}// </editor-fold>
// Variables declaration - do not modify
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jmCArchivo;
private javax.swing.JMenu jmCapturar;
private javax.swing.JMenu jmDispositivos;
private javax.swing.JPanel panelCam;
// End of variables declaration
}
AuxClass.java
import java.awt.Component;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.imageio.ImageIO;
import javax.media.Buffer;
import javax.media.CannotRealizeException;
import javax.media.CaptureDeviceInfo;
import javax.media.Format;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.NoPlayerException;
import javax.media.Player;
import javax.media.cdm.CaptureDeviceManager;
import javax.media.control.FormatControl;
import javax.media.control.FrameGrabbingControl;
import javax.media.format.RGBFormat;
import javax.media.format.VideoFormat;
import javax.media.format.YUVFormat;
import javax.media.util.BufferToImage;
import javax.swing.JFileChooser;
import javax.swing.JMenu;
import javax.swing.JOptionPane;
public class AuxClass implements WindowListener,ActionListener{
private final CameraApplet padreApplet;
public AuxClass(CameraApplet padreApplet){this.padreApplet = padreApplet;}
//Menu Actions
#Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("En Archivo")){
AuxClass.saveImageFile(AuxClass.capturePhoto(padreApplet.getPlayer()),
AuxClass.SaveFileAsDialog(padreApplet));
}
}
#Override
public void windowClosing(WindowEvent e) {AuxClass.stopPlayer(padreApplet.getPlayer());}
#Override
public void windowOpened(WindowEvent e) {
}
#Override
public void windowClosed(WindowEvent e) {
}
#Override
public void windowIconified(WindowEvent e) {
}
#Override
public void windowDeiconified(WindowEvent e) {
}
#Override
public void windowActivated(WindowEvent e) {
}
#Override
public void windowDeactivated(WindowEvent e) {
}
//This method handles the Saving image file as. Jpg
public static File SaveFileAsDialog(Component padre){
JFileChooser f;
File imageFile = null;
String imagePath = "";
f = new JFileChooser();
f.setDialogTitle("Save File As...");
f.showSaveDialog(padre);
if(f.getSelectedFile() != null){
imagePath = f.getSelectedFile().getAbsolutePath();
if (imagePath.lastIndexOf(".") > 0)
imagePath = imagePath.substring(0,imagePath.lastIndexOf("."));
imagePath = imagePath + ".jpg";
imageFile = new File(imagePath);
}
return imageFile;
}
public static void showErrorMessage(Component padre,String mensaje){
JOptionPane.showMessageDialog(padre,mensaje,"Captura Camara Web ",JOptionPane.ERROR_MESSAGE);
}
//This is the link between camera and the player class first time you turn the camera on
public static void setCameraApplet(CameraApplet camera,String device,int format){
Player player = AuxClass.createPlayer(device, format);
camera.setPlayer(player);
AuxClass.startPlayer(player);
camera.getCamera().add(player.getVisualComponent());
}
//----------------------------------------Player methods----------------------------------------
public static void startPlayer(Player p){
if(p!=null) p.start();
}
public static void stopPlayer(Player p){
if(p!=null){
p.stop();
p.deallocate();
p.close();
}
}
public static Image capturePhoto(Player p){
Image img = null;
if(p != null){
FrameGrabbingControl fgc = (FrameGrabbingControl)p.getControl("javax.media.control.FrameGrabbingControl");
Buffer buf = fgc.grabFrame();
BufferToImage btoi = new BufferToImage((VideoFormat)buf.getFormat());
img = btoi.createImage(buf);
}
else{
AuxClass.showErrorMessage(null, "¡Player has not started yet!");
}
return img;
}
public static void saveImageFile(Image img,File imagenArch){
String format = "JPG";
try {
if(img !=null && imagenArch!=null)
ImageIO.write((RenderedImage) img, format , imagenArch);
}
catch (IOException e) {
AuxClass.showErrorMessage(null, "Disk write error: " + e.toString());
}
}
//JDevices methods
//returns webCam's name selected
public static CaptureDeviceInfo returnDevice(String name){
return CaptureDeviceManager.getDevice(name);
}
//open webCamera selected
public static MediaLocator openDevice(CaptureDeviceInfo cdi){
return cdi.getLocator();
}
//Crea un Player a partir del nombre del dispositivo y del indice del formáto que se desea aplicar
public static Player createPlayer(String device,int f){
Player p = null;
try {
p = Manager.createRealizedPlayer(openDevice(returnDevice(device)));
Format []formats;
formats = getFormats(device);
FormatControl formatControl = (FormatControl)p.getControl("javax.media.control.FormatControl");
formatControl.setFormat (formats[f]);
}
catch (CannotRealizeException | IOException | NoPlayerException e) {
AuxClass.showErrorMessage(null, "Input-Output Error: \n" + e.toString());
}
return p;
}
//Returns available formats, passing device's name
public static Format[] getFormats(String name){
CaptureDeviceInfo cdi1 = returnDevice(name);
Format []formats = cdi1.getFormats();
return formats;
}
//Switches player's resolutions
public static void changeResolution(Player p,String device,int format){
if(p != null) p.stop();
Format []formats = getFormats(device);
FormatControl formatControl = (FormatControl)p.getControl("javax.media.control.FormatControl");
formatControl.setFormat (formats[format]);
p.start();
}
//Loads all the cameras detected and its actions within a JMenu object
public static void DevicesMenuApplet(CameraApplet camera, JMenu devices){
List<String> cameraList = detectAvailableWebCameras();
Format[] formatsArray;
for(int j= 0; j< cameraList.size(); j++){
JMenu menuFormato = new JMenu(cameraList.get(j));
JMenuFormato cameraRes = null;
CaptureDeviceInfo dev = CaptureDeviceManager.getDevice(cameraList.get(j));
formatsArray = dev.getFormats();
//get the formats/resolutions availables:
for(int i = 0; i < formatsArray.length; i++){
if(formatsArray[i].getEncoding().compareTo("yuv") == 0){
//this returns a menu element with label of the resolution and its actionlistener
cameraRes = new JMenuFormato(cameraList.get(j),
formatsArray[i].getEncoding()+" "+
((YUVFormat)formatsArray[i]).getSize().width + "x" +
((YUVFormat)formatsArray[i]).getSize().height,
i,
((YUVFormat)formatsArray[i]).getSize().width ,
((YUVFormat)formatsArray[i]).getSize().height ,
camera,
camera.getCamera());
}
else
if(formatsArray[i].getEncoding().compareTo("rgb") == 0){
cameraRes = new JMenuFormato(cameraList.get(j),
formatsArray[i].getEncoding()+" "+
((RGBFormat)formatsArray[i]).getSize().width+"x"+
((RGBFormat)formatsArray[i]).getSize().height,
i,
((RGBFormat)formatsArray[i]).getSize().width,
((RGBFormat)formatsArray[i]).getSize().height,
camera,
camera.getCamera());
}
menuFormato.add(cameraRes);//Adds the menu to JMenu list
}
devices.add(menuFormato);
}
}
//Detects all the camera devices detected inside a List
public static List<String> detectAvailableWebCameras(){
//make a reference to a JMF function for obtaining the devices
List<String> deviceList = CaptureDeviceManager.getDeviceList(null);
List<String> cameraList = new ArrayList<>();
Iterator it = deviceList.iterator();
String name = ""; //Stores all the names of the devices
while (it.hasNext()){ //Makes a cycle for listing all stored devices
CaptureDeviceInfo cdi = (CaptureDeviceInfo)it.next(); //Get device info
name = cdi.getName(); //Get detected device's name
//Filter only camera devices
if(name.indexOf("Image") != -1){cameraList.add(name);}
}
return cameraList;
}
}
JMenuFormato.java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
//this class implements logic for obtaining menus and resolutions JFrame
public class JMenuFormato extends JMenuItem implements ActionListener{
private final int width;
private final int high;
private final int ordinal;
private final JPanel modifiable;
private final String device;
private final CameraApplet cameraApplet;
//Constructores (Version Applet y version JFrame)
public JMenuFormato(String device,String label,int ordinal,int width,int high,CameraApplet cameraApplet,JPanel modifiable){
super(label);
this.modifiable = modifiable;
this.width = width;
this.high = high;
this.cameraApplet = cameraApplet;
this.device = device;
this.ordinal = ordinal;
this.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
//Acciones para Applet (Class)
if(cameraApplet.getPlayer() == null){
AuxClass.setCameraApplet(cameraApplet, device, ordinal);
}
else{
AuxClass.changeResolution(cameraApplet.getPlayer(),device, ordinal);
}
cameraApplet.setSize(width+200, high+200);
}
}
index.html
<html>
<head>
<title>WebCam app</title>
</head>
<body>
<div><applet code="CameraApplet.class" archive="CapturaCamaraWeb.jar" width="680" height="840"></applet></div>
</body>
</html>
I want to create an image from a video using xuggler. The sample code provided generates images from video in an interval, I modified it so that it only generates one image from video. BUT, it looks like it is actually looping through the whole video rather than just taking a snapshot of a specific time then end.
How can I properly generate ONE image from a video without looping through the whole video? On shorter videos this is fine but on hr+ videos, this would become a huge problem.
Below is my code:
import javax.imageio.ImageIO;
import java.io.File;
import java.awt.image.BufferedImage;
import java.util.Random;
import com.xuggle.mediatool.IMediaReader;
import com.xuggle.mediatool.MediaListenerAdapter;
import com.xuggle.mediatool.ToolFactory;
import com.xuggle.mediatool.event.IVideoPictureEvent;
import com.xuggle.xuggler.Global;
public class Test extends MediaListenerAdapter {
public static final double SECONDS_BETWEEN_FRAMES = 1;
public static final long MICRO_SECONDS_BETWEEN_FRAMES = (long)(Global.DEFAULT_PTS_PER_SECOND * SECONDS_BETWEEN_FRAMES);
private int mVideoStreamIndex = -1;
boolean takeImage = true;
public static void main(String[] args) {
new Test("src/main/Wildlife_ 512kb, hkf.mp4");
}
public Test(String filename) {
System.out.println("starting the xuggler");
IMediaReader reader = ToolFactory.makeReader(filename);
reader.setBufferedImageTypeToGenerate(BufferedImage.TYPE_3BYTE_BGR);
reader.addListener(this);
while (reader.readPacket() == null) { do { } while(false); }
}
public void onVideoPicture(IVideoPictureEvent event) {
try {
if (event.getStreamIndex() != mVideoStreamIndex) {
if (-1 == mVideoStreamIndex) {
mVideoStreamIndex = event.getStreamIndex();
} else {
return;
}
}
if (event.getTimeStamp() > MICRO_SECONDS_BETWEEN_FRAMES && takeImage) {
Random random = new Random();
File file = new File("/Users/yao/__TEMP__/media_upload_temp/" + random.nextInt(Integer.MAX_VALUE) + ".png");
ImageIO.write(event.getImage(), "png", file);
double seconds = ((double)event.getTimeStamp()) / Global.DEFAULT_PTS_PER_SECOND;
System.out.printf("at elapsed time of %6.3f seconds wrote: %s\n", seconds, file);
takeImage = false;
}
} catch (Exception e) { e.printStackTrace(); }
}
}
Basically, I just aded a boolean field and use that to manage when to break out of loop/video after one image was capture.
while (reader.readPacket() == null) {
if (!takeImage) {
reader.removeListener(this);
break;
}
}
I am currently trying to turn my JFrame into a JApplet.
It runs fine in eclipse as an applet but when I try to use it on my website it gives me an error.
Here is my Applet: http://tekhaxs.com/applet.java
You can view my java source there ^^ or below.
here is the error: http://tekhaxs.com/?page_id=146
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import javax.imageio.ImageIO;
public class applet extends JApplet
{
JButton newBut = new JButton("New");
JButton backBut = new JButton("Back");
Font font;
BufferedImage img = null;
BufferedImage background = null;
URL url = null;
String extension;
int linkNum = 0;
int total = 0;
int backNum = 0;
String appending;
ArrayList<String> az = new ArrayList<String>();
ArrayList<String> history = new ArrayList<String>();
public void init() //initialize everything.
{
this.setLayout(null);
backBut.addActionListener(new buttonListener());
this.add(backBut);
backBut.setBounds(300, 5, 80, 35);
newBut.addActionListener(new buttonListener());
this.add(newBut);
newBut.setBounds(400, 5, 80, 35);
font = new Font("arial",Font.BOLD,20);
makeArrays();
changeUrlExtension();
try {
background = ImageIO.read(new URL("http://puu.sh/3a7KY/d2ba48949c.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
class buttonListener implements ActionListener //Button Listener for next.
{
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == backBut){
backNum++;
extension = history.get(total - backNum - 1);
repaint();
}else if(e.getSource() == newBut){
backNum = 0;
changeUrlExtension();
history.add(extension);
total++;
repaint();
}
}
}
public void changeUrlExtension(){
int a1 = (int) Math.round(Math.random() * 51);
int a2 = (int) Math.round(Math.random() * 51);
int a3 = (int) Math.round(Math.random() * 51);
String aaa = (az.get(a3)+az.get(a2)+az.get(a1));
int linkNum = (int) Math.round(Math.random() * 13) + 20;
extension = linkNum+aaa;
try {
url = new URL("http://puu.sh/"+extension+".png");
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
public void paint(Graphics g) { //Paints Graphics for frame.
g.drawImage(background, 0, 0, null);
g.drawImage(getImage(), 5, 50, null);
g.setColor(Color.MAGENTA);
g.drawString("Current Picture: http://puu.sh/"+extension+".png", 10,40);
g.setFont(font);
g.drawString("Picture Number: "+(total - backNum), 10,20);
}
public Image getImage(){ //Returns Image from url.
try {
url = new URL("http://puu.sh/"+extension+".png");
} catch (IOException e) {
e.printStackTrace();
}
try {
img = ImageIO.read(url);
System.out.println(total+". "+url);
} catch (IOException e) {
changeUrlExtension();
getImage();
}
return img;
}
public void makeArrays(){ //Makes az Array.
az.add("A");
az.add("a");
az.add("B");
az.add("b");
az.add("C");
az.add("c");
az.add("D");
az.add("d");
az.add("E");
az.add("e");
az.add("F");
az.add("f");
az.add("G");
az.add("g");
az.add("H");
az.add("h");
az.add("I");
az.add("i");
az.add("J");
az.add("j");
az.add("K");
az.add("k");
az.add("L");
az.add("l");
az.add("M");
az.add("m");
az.add("N");
az.add("n");
az.add("O");
az.add("o");
az.add("P");
az.add("p");
az.add("Q");
az.add("q");
az.add("R");
az.add("r");
az.add("S");
az.add("s");
az.add("T");
az.add("t");
az.add("U");
az.add("u");
az.add("V");
az.add("v");
az.add("W");
az.add("w");
az.add("X");
az.add("x");
az.add("Y");
az.add("y");
az.add("Z");
az.add("z");
}
}
Here is the html code I use to call my JApplet.
<applet code="http://tekhaxs.com/applet.java" width="400" height="400">
If your browser was Java-enabled, a Puush Browser would appear here.
</applet>
Any suggestions on how to fix this error?
You need to provide the class file of your applet in the code attribute:
<applet code="applet.class" width="400" height="400">
This should work if the class file is at the same location as your html file. If the class file is at a different location, you need to specify the location through an additional codebase attribute, e.g. if the class file is located in a bin subdirectory, specify
<applet code="applet.class" codebase="bin" width="400" height="400">
See http://www.duckware.com/applets/reference.html for additional information.
Essentially,
code refers to the class of the main applet class, including any package names, and with a .class postfix, like in code="com.example.SampleApplet.class".
codebase is a URL (either relative or absolute) which refers to the location where the class file specified in code can be found. If it is the same location as the html file, codebase can be omitted.
now I am getting a different error.
Access denied ("java.net.SocketPermission""Puu.sh:80""connect,ressolve")
Your applet code does not have the necessary access rights to use sockets (which is required to access puu.sh which you do in your code). Note that applets are running on the client machine, and by default they are not allowed any access outside their sandbox.
You can adjust the privileges by creating a so-called policy file on the client machine - See http://download.java.net/jdk8/docs/technotes/guides/security/PolicyFiles.html for more information. Note that this needs to be done on the client side.
I would try to put the images on the same server where your applet resides. Then you should be able to download them without modifying the security policies.
I am trying to extract an image from the requested website, then save it to a folder. The only problem is that the website I am pulling the image from has multiple image formats. So the extension for the image would be either png, jpg, or gif. I need to save all of these, but I do not know how to tell my program to extract multiple formats rather than just one..
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Main {
public static void main( String[] args )
{
int avatarnum = 1;
String extension = null;
BufferedImage image = null;
extension = "jpg";
while(avatarnum <= 1000){
try {
URL url = new URL("http://forum.blockland.us/avatarUpload/avatar_"+avatarnum+"."+extension);
image = ImageIO.read(url);
try{
ImageIO.write(image, extension,new File("C:\\test\\"+avatarnum+"."+extension));
System.out.println("Write successful");
avatarnum ++;
} catch(Exception e){
System.out.println("Printing stacktrace");
e.printStackTrace();
}
avatarnum ++;
} catch (IOException e) {
System.out.println("File not found! " + avatarnum);
System.out.println("Adding one to variable and retrying..");
avatarnum ++;
}
}
System.out.println("Done");
}
}
As of now, only jpg images are being extracted from the website and saved to the folder.
For testing purposes it will only pull 1,000 images from the site.
I will be using this to make an "avatar database" if anyone was wondering.
Thanks a ton guys!
You need iterate over multiple image formats (extensions):
public static void main(String[] args) {
int avatarnum = 1;
BufferedImage image = null;
String[] extensions = { "jpg", "png", "gif", "bmp" };
while (avatarnum <= 1000) {
for (String extension : extensions) {
try {
URL url = new URL("http://forum.blockland.us/avatarUpload/avatar_" + avatarnum + "." + extension);
image = ImageIO.read(url);
try {
ImageIO.write(image, extension, new File("C:\\test\\" + avatarnum + "." + extension));
System.out.println("Write successful");
} catch (Exception e) {
System.out.println("Error on save the image");
}
} catch (IOException e) {
System.out.println("File not found! " + avatarnum + "." + extension);
}
}
avatarnum++;
}
System.out.println("Done");
}
Use an array with all valid extensions
String[] extensions = {"jpg", "png", "gif" };
And loop over all of them when retreive the URL
try {
for (String extension: extensions){
try {
URL url = new URL("http://forum.blockland.us/avatarUpload/avatar_"+avatarnum+"."+extension);
image = ImageIO.read(url);
} catch (Exception e){
//Wrong extension (or other kind of error)
}
}
...
For every image, it will fail with the wrong extensions, but will retreive the one with the correct
Java Sound offers FloatControl instances for various sound line functionality, and both a MASTER_GAIN & VOLUME control type.
Can these controls be used to change the system volume?
No, it cannot. Here is source adapted from an answer to Adjusting master volume on coderanch. The source iterates the available lines, checks if they have a control of the right type, and if so, puts them in a GUI attached to a JSlider
import java.awt.*;
import javax.swing.*;
import javax.sound.sampled.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class SoundMixer {
public Component getGui() {
JPanel gui = new JPanel(new GridLayout(0,1));
Mixer.Info[] mixers = AudioSystem.getMixerInfo();
System.out.println(
"There are " + mixers.length + " mixer info objects");
for (Mixer.Info mixerInfo : mixers) {
System.out.println("mixer name: " + mixerInfo.getName());
Mixer mixer = AudioSystem.getMixer(mixerInfo);
Line.Info[] lineInfos = mixer.getSourceLineInfo();
for (Line.Info lineInfo : lineInfos) {
System.out.println(" Line.Info: " + lineInfo);
try {
Line line = mixer.getLine(lineInfo);
FloatControl volCtrl = (FloatControl)line.getControl(
FloatControl.Type.MASTER_GAIN);
VolumeSlider vs = new VolumeSlider(volCtrl);
gui.add( new JLabel(volCtrl.toString()) );
gui.add( vs.getVolume() );
System.out.println(
" volCtrl.getValue() = " + volCtrl.getValue());
} catch (LineUnavailableException e) {
e.printStackTrace();
} catch (IllegalArgumentException iaEx) {
System.out.println(" " + iaEx);
}
}
}
return gui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
SoundMixer sm = new SoundMixer();
Component c = sm.getGui();
JOptionPane.showMessageDialog(null, c);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
class VolumeSlider {
JSlider volume;
VolumeSlider(final FloatControl volumeControl) {
volume = new JSlider(
(int) volumeControl.getMinimum() * 100,
(int) volumeControl.getMaximum() * 100,
(int) volumeControl.getValue() * 100);
ChangeListener listener = new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
float val = volume.getValue() / 100f;
volumeControl.setValue(val);
System.out.println(
"Setting volume of " + volumeControl.toString() +
" to " + val);
}
};
volume.addChangeListener(listener);
}
public JSlider getVolume() {
return volume;
}
}
On this Windows 7 machine I get two controls, both from the "Java Sound Audio Engine". Neither has any effect on the current system volume.
run:
There are 4 mixer info objects
mixer name: Primary Sound Driver
Line.Info: interface SourceDataLine supporting 8 audio formats, and buffers of at least 32 bytes
java.lang.IllegalArgumentException: Unsupported control type: Master Gain
Line.Info: interface Clip supporting 8 audio formats, and buffers of at least 32 bytes
java.lang.IllegalArgumentException: Unsupported control type: Master Gain
mixer name: Speakers (VIA High Definition Audio)
Line.Info: interface SourceDataLine supporting 8 audio formats, and buffers of at least 32 bytes
java.lang.IllegalArgumentException: Unsupported control type: Master Gain
Line.Info: interface Clip supporting 8 audio formats, and buffers of at least 32 bytes
java.lang.IllegalArgumentException: Unsupported control type: Master Gain
mixer name: Java Sound Audio Engine
Line.Info: interface SourceDataLine supporting 8 audio formats
volCtrl.getValue() = 0.0
Line.Info: interface Clip supporting 8 audio formats, and buffers of 0 to 4194304 bytes
volCtrl.getValue() = 0.0
mixer name: Port Speakers (VIA High Definition A
Setting volume of Master Gain with current value: 0.0 dB (range: -80.0 - 13.9794) to 0.0
Setting volume of Master Gain with current value: 0.0 dB (range: -80.0 - 13.9794) to -0.41
Setting volume of Master Gain with current value: 0.0 dB (range: -80.0 - 13.9794) to -0.68
...
Swap FloatControl.Type.MASTER_GAIN for FloatControl.Type.VOLUME to see.. no controls.
add following line just after Line is initialized. this is required to open the line.
boolean opened = line.isOpen() || line instanceof Clip;
if(!opened){
System.out.println("Line is not open, trying to open it...");
line.open();
opened = true;
}
try this it wont disappoint you.... we can modify upper example accordingly.
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.Line;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.Mixer;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
public class SoundMeter {
JFrame j;
public SoundMeter() {
j = new JFrame("SoundMeter");
j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
j.setLayout(new BoxLayout(j.getContentPane(), BoxLayout.Y_AXIS));
printMixersDetails();
j.setVisible(true);
}
public void printMixersDetails(){
javax.sound.sampled.Mixer.Info[] mixers = AudioSystem.getMixerInfo();
System.out.println("There are " + mixers.length + " mixer info objects");
for(int i=0;i<mixers.length;i++){
Mixer.Info mixerInfo = mixers[i];
System.out.println("Mixer Name:"+mixerInfo.getName());
Mixer mixer = AudioSystem.getMixer(mixerInfo);
Line.Info[] lineinfos = mixer.getTargetLineInfo();
for(Line.Info lineinfo : lineinfos){
System.out.println("line:" + lineinfo);
try {
Line line = mixer.getLine(lineinfo);
line.open();
if(line.isControlSupported(FloatControl.Type.VOLUME)){
FloatControl control = (FloatControl) line.getControl(FloatControl.Type.VOLUME);
System.out.println("Volume:"+control.getValue());
JProgressBar pb = new JProgressBar();
// if you want to set the value for the volume 0.5 will be 50%
// 0.0 being 0%
// 1.0 being 100%
control.setValue((float) 0.5);
int value = (int) (control.getValue()*100);
pb.setValue(value);
j.add(new JLabel(lineinfo.toString()));
j.add(pb);
j.pack();
}
} catch (LineUnavailableException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
new SoundMeter();
}
}
I am using VOLUME control type. This code works for me for XP and WIN 7, but not for OSX. See my example:
import java.io.IOException;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.Line;
import javax.sound.sampled.Mixer;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class VolumeExample extends JPanel {
/**
* #return main sound control object
* #throws Exception for any problem
*/
private FloatControl getVolumeControl() throws Exception {
try {
Mixer.Info mixers[] = AudioSystem.getMixerInfo();
for (Mixer.Info mixerInfo : mixers) {
Mixer mixer = AudioSystem.getMixer(mixerInfo);
mixer.open();
//we check only target type lines, because we are looking for "SPEAKER target port"
for (Line.Info info : mixer.getTargetLineInfo()) {
if (info.toString().contains("SPEAKER")) {
Line line = mixer.getLine(info);
try {
line.open();
} catch (IllegalArgumentException iae) {}
return (FloatControl) line.getControl(FloatControl.Type.VOLUME);
}
}
}
} catch (Exception ex) {
System.out.println("problem creating volume control object:"+ex);
throw ex;
}
throw new Exception("unknown problem creating volume control object");
}
VolumeExample() {
JSlider slider = new JSlider();
add(slider);
//this is for setting the value
slider.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
JSlider src = (JSlider)e.getSource();
//if (src.getValueIsAdjusting()) return; //optional
if (src.getValue() % 5 !=0) return;
float value = src.getValue() / 100.0f;
try {
getVolumeControl().setValue(value);
//you can put a click play code here to have nice feedback when moving slider
} catch (Exception ex) {
System.out.println(ex);
}
}
});
//and this is for getting the value
try {
slider.setValue((int) (getVolumeControl().getValue()*100.0f));
} catch (Exception e) {
System.out.println(e);
}
}
}
I was recently focusing the same problem. In the end I decided to write a little Program called VolumeChanger.exe in C++ and call this from java. Works great. You can call a exe from java with
Process process = new ProcessBuilder(vcpath,"-u").start();
wehre vcpath is the path to your exe file (could be realtive of course).
If you are interested how I used this tool visit me on muteFritz
If you are interested in the whole source code feel free to PM me...
Here is a solution that works ONLY on OS X (I am running 10.10):
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
public class MasterVolume
{
public void setMasterVolume(float value)
{
String command = "set volume " + value;
try
{
ProcessBuilder pb = new ProcessBuilder("osascript","-e",command);
pb.directory(new File("/usr/bin"));
System.out.println(command);
StringBuffer output = new StringBuffer();
Process p = pb.start();
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = reader.readLine())!= null)
{
output.append(line + "\n");
}
System.out.println(output);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
You would call the method like this:
MasterVolume.setMasterVolume(3.5f);
Which would set the volume at 50% since the range is .1 to 7.0