Extracting images from URL with multiple extensions - java

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

Related

Bengali Joint letters in Kalpurush font in java messed up

I have written a program (collecting from various sources, I am a beginner) in Java that takes a text(bengali) written in a .txt file and converts it to a .bmp image using the drawString function. The code is :
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
import java.util.*;
import java.awt.font.*;
import java.awt.geom.*;
class TextToImageDemo
{
public static void main(String[] args) throws IOException
{
String sampleText = "আমার",s="নাম";
BufferedReader br = null;
for (int u=1;u<=9;u++)
{
try
{
br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("E:\\Java\\bengtext\\f2-0"+u+".txt")),"UTF-8"));
while ((sampleText = br.readLine()) != null)
{
System.out.println(sampleText);
s=sampleText;
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (br != null)br.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
//Image file name
String fileName = "Image";
//create a File Object
File newFile= new File("./" + fileName + ".jpeg");
//create the font you wish to use
Font font = new Font(/*Lohit Bengali*/"Kalpurush", Font.PLAIN, 50);
//create the FontRenderContext object which helps us to measure the text
FontRenderContext frc = new FontRenderContext(null, true, true);
//create a BufferedImage object
BufferedImage image = new BufferedImage(2000, 200, BufferedImage.TYPE_INT_RGB);
//calling createGraphics() to get the Graphics2D
Graphics2D g = image.createGraphics();
System.out.println(s);
//set color and other parameters
g.setColor(Color.WHITE);
g.fillRect(0, 0, 2000, 200);
g.setColor(Color.BLACK);
g.setFont(font);
FontMetrics fm=g.getFontMetrics();
Rectangle r=new Rectangle(fm.getStringBounds(s, g).getBounds());
String d=s.substring(1,s.length());
g.drawString(d, image.getWidth()/2-r.width/2, image.getHeight()/2+r.height/2);
//releasing resources
g.dispose();
try
{
FileOutputStream fos = new FileOutputStream("E:\\Java\\bengtext\\f2-0"+u+".bmp");
ImageIO.write(image,"bmp",fos);
fos.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
}
My main problem lies in the fact that a text like
দ্বিতীয়তা , একাগ্রতা , " জ্ঞান আহরনের একটি মাত্র উপায়
is formed like
How can this be solved?
Edit:
On checking all the 263 fonts available , I found only 6 of them were able to display bengali somewhat correctly. But in everyone of them the problem with the joint words lie as shown in the above picture. So question is : What is the exact problem happening here? Is JAVA not being able to read the joint words correctly, or is it not being able to draw them correctly ?
And secondly , how to make java draw the joint words correctly?

How to read a GIF with Java's ImageIO and preserve the animation?

I'm working on a project and the goal is to have all images read with ImageIO. This seems to work for everything except GIF images (which display as a static image of the initial frame). I have seen other answers on Stack Overflow and from a thread on the Oracle forums but most require using Java's File class which I can't access due to the program's SecurityManager. I've been able to break the GIF down into an Image array and edit the metadata, but after stitching everything back together I can only display a single image.
Below is a SSCCE for the program:
import java.awt.Image;
import java.awt.Toolkit;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class GifRenderer {
public static void main(String[] args) throws Exception {
Image image = null;
byte[] imageByteArray = null;
try {
String location = "http://i.imgur.com/Ejh5gJa.gif";
imageByteArray = createByteArray(location);
// This works, but I'm trying to use ImageIO
//image = Toolkit.getDefaultToolkit().createImage(imageByteArray);
InputStream in = new ByteArrayInputStream(imageByteArray);
image = ImageIO.read(in);
} catch (IOException e) {
e.printStackTrace();
}
JFrame frame = new JFrame();
frame.setSize(300, 300);
JLabel label = new JLabel(new ImageIcon(image));
frame.add(label);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
// Constraint: This method simulates how the image is originally received
private static byte[] createByteArray(String urlString) throws IOException {
URL url = new URL(urlString);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream is = null;
try {
is = url.openStream ();
byte[] byteChunk = new byte[4096];
int n;
while ( (n = is.read(byteChunk)) > 0 ) {
baos.write(byteChunk, 0, n);
}
} catch (IOException e) {
e.printStackTrace ();
} finally {
if (is != null) { is.close(); }
}
return baos.toByteArray();
}
}
Some constraints worth mentioning that might not be clear:
The image is originally received as a byte array
The image should be read by ImageIO
The final result should be an Image object
The File class can't be accessed
Given these constraints is there still a way to use ImageIO to display the GIF the same way Toolkit.getDefaultToolkit().createImage() would display the image?

What is correct way to get ONE screenshot/snapshot of a video using xuggler?

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;
}
}

ImageIcon update in Java (from the internet)?

I have some URL with an image there. This image updates during each request (that is, each request to the (same) URL returns a new image). Say, this URL points to CAPTCHA.
My goal is to load and display several such images in my program.
The following code loads these images to my local filesystem and works OK (that is, all the images are different, unique):
String filePath;
String urlPath;
int numOfFilesToDownload;
//Here filePath and urlPath are initialized.
//filePath points to the directory, where to save images
//urlPath is the url from where to download images
//numOfFilesToDownload is the number of files to download
for(int i = 0; i < numOfFilesToDownload; i++){
//Initializing connection
URL url = new URL(urlPath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//Downloading image
try(InputStream is = conn.getInputStream();
FileOutputStream os = new FileOutputStream(filePath + "img" + i + ".jpg")){
int b;
while((b = is.read()) != -1)
os.write(b);
}
}
But something weird happens, when I try the following thing:
for(int i = 0; i < numOfFilesToDownload; i++){
//Initializing image from the url
URL url = new URL(urlPath);
javax.swing.ImageIcon ico = new javax.swing.ImageIcon(url);
//Showing the graphical dialog window with the image
javax.swing.JOptionPane.showMessageDialog(null, ico);
}
In the latter case, each dialog contains the same image, namely the one, downloaded during the very first iteration.
Also, the experiments show, that if you concatenate "?r=" to the urlPath (that is, a simple GET request parameter), the url will still be valid.
And the following code appears to be valid and does exactly what it has (namely each image shown is different from the previous):
for(int i = 0; i < numOfFilesToDownload; i++){
//Initializing image from the url
URL url = new URL(urlPath + "?r=" + i);
javax.swing.ImageIcon ico = new javax.swing.ImageIcon(url);
//Showing the graphical dialog window with the image
javax.swing.JOptionPane.showMessageDialog(null, ico);
}
Hence I can make a conclusion, that ImageIcon somehow remembers the URLs it handled and simply does not bother to perform the same work twice... Why and how? There's nothing in javadocs about it.
When I tried a variation of your code, it worked fine. My SSCCE:
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
public class TestUrls {
public static final String BASE_URL_PATH = "http://static.ed.edmunds-media.com/" +
"unversioned/adunit/homepage_showcase/";
public static final String[] URL_PATHS = {
"honda-odyssey-2013.png",
"chevrolet-impala-2013.png",
"mazda-cx9-2013.png",
"toyota-rav4-2013-2.png"
};
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
for (String urlPath : URL_PATHS) {
String fullUrlPath = BASE_URL_PATH + urlPath;
try {
URL url = new URL(fullUrlPath);
BufferedImage img = ImageIO.read(url);
ImageIcon icon = new ImageIcon(img);
JOptionPane.showMessageDialog(null, icon);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
}
}

Alternative to java.awt.imageproducer for android

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.

Categories