下面列出了javax.swing.event.MenuListener#javax.imageio.ImageIO 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static byte[] getImageBytes(Image image, String type) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedImage bufImage = convertToBufferedImage(image);
ImageWriter writer = null;
Iterator<ImageWriter> i = ImageIO.getImageWritersByMIMEType(type);
if (i.hasNext()) {
writer = i.next();
}
if (writer != null) {
ImageOutputStream stream = null;
stream = ImageIO.createImageOutputStream(baos);
writer.setOutput(stream);
writer.write(bufImage);
stream.close();
return baos.toByteArray();
}
return null;
}
/**
* 等比例缩放
* <br/>判断图像的宽度,若是宽度大于传入的值,则进行等比例压缩到指定宽高。若是图片小于指定的值,则不处理
* @param inputStream 原图
* @param maxWidth 缩放后的宽度。若大于这个宽度才会进行等比例缩放。否则不进行处理。传入0则不处理,忽略
* @param suffix 图片的后缀名,如png、jpg
* @return 处理好的
*/
public static InputStream proportionZoom(InputStream inputStream,int maxWidth,String suffix){
if(inputStream == null){
return null;
}
if(maxWidth == 0 || maxWidth < 0){
return inputStream;
}
try {
BufferedImage bi = ImageIO.read(inputStream);
BufferedImage b = proportionZoom(bi, maxWidth);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(b, suffix, os);
InputStream is = new ByteArrayInputStream(os.toByteArray());
return is;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public void doTest() {
File pwd = new File(".");
try {
File f = File.createTempFile("transparency_test_", ".gif", pwd);
System.out.println("file: " + f.getCanonicalPath());
ImageWriter w = ImageIO.getImageWritersByFormatName("GIF").next();
ImageWriterSpi spi = w.getOriginatingProvider();
boolean succeed_write = ImageIO.write(src, "gif", f);
if (!succeed_write) {
throw new RuntimeException("Test failed: failed to write src.");
}
dst = ImageIO.read(f);
checkResult(src, dst);
} catch (IOException e) {
throw new RuntimeException("Test failed.", e);
}
}
public static void main(String[] args) throws IOException {
if (args.length > 0) {
format = args[0];
}
writer = ImageIO.getImageWritersByFormatName(format).next();
file_suffix =writer.getOriginatingProvider().getFileSuffixes()[0];
BufferedImage src = createTestImage();
EncodeSubImageTest m1 = new EncodeSubImageTest(src);
m1.doTest("test_src");
BufferedImage sub = src.getSubimage(subImageOffset, subImageOffset,
src.getWidth() - 2 * subImageOffset,
src.getHeight() - 2 * subImageOffset);
EncodeSubImageTest m2 = new EncodeSubImageTest(sub);
m2.doTest("test_sub");
}
@Override
public InputStream convert(InputStream fromInputSource, String toMimeType) {
try {
// read a jpeg from a inputFile
BufferedImage bufferedImage = ImageIO.read(fromInputSource);
// write the bufferedImage back to outputFile
ImageIO.write(bufferedImage, "png", new File("/tmp/temp.png"));
return new FileInputStream("/tmp/temp.png");
}
catch (Exception e) {
e.printStackTrace();
}
finally {
IOUtils.closeQuietly(fromInputSource);
}
return null;
}
private static void screenshotStencil(int x) {
Dimension d = GuiDraw.displayRes();
ByteBuffer buf = BufferUtils.createByteBuffer(d.width * d.height);
BufferedImage img = new BufferedImage(d.width, d.height, BufferedImage.TYPE_INT_RGB);
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glReadPixels(0, 0, d.width, d.height, GL_STENCIL_INDEX, GL_UNSIGNED_BYTE, buf);
for(int i = 0; i < d.width; i++)
for(int j = 0; j < d.height; j++)
img.setRGB(i, d.height-j-1, buf.get(j * d.width + i) == 0 ? 0 : 0xFFFFFF);
try {
ImageIO.write(img, "png", new File("stencil"+x+".png"));
} catch (IOException e) {
e.printStackTrace();
}
}
private static NbImageIcon iconFromResourceName(String resName, FileObject srcFile) {
ClassPath cp = ClassPath.getClassPath(srcFile, ClassPath.SOURCE);
FileObject fo = cp.findResource(resName);
if (fo == null) {
cp = ClassPath.getClassPath(srcFile, ClassPath.EXECUTE);
fo = cp.findResource(resName);
}
if (fo != null) {
try {
try {
Image image = ImageIO.read(fo.getURL());
if (image != null) { // issue 157546
return new NbImageIcon(TYPE_CLASSPATH, resName, new ImageIcon(image));
}
} catch (IllegalArgumentException iaex) { // Issue 178906
Logger.getLogger(IconEditor.class.getName()).log(Level.INFO, null, iaex);
return new NbImageIcon(TYPE_CLASSPATH, resName, new ImageIcon(fo.getURL()));
}
} catch (IOException ex) { // should not happen
Logger.getLogger(IconEditor.class.getName()).log(Level.WARNING, null, ex);
}
}
return null;
}
public static void zoom(int maxWidth, String srcImageFile, String destImageFile) {
try {
BufferedImage srcImage = ImageIO.read(new File(srcImageFile));
int srcWidth = srcImage.getWidth();
int srcHeight = srcImage.getHeight();
// 当宽度在 maxWidth 范围之内,直接copy
if (srcWidth <= maxWidth) {
FileUtils.copyFile(new File(srcImageFile), new File(destImageFile));
}
// 当宽度超出 maxWidth 范围,将宽度变为 maxWidth,高度按比例缩放
else {
float scalingRatio = (float) maxWidth / (float) srcWidth; // 计算缩放比率
float maxHeight = ((float) srcHeight * scalingRatio); // 计算缩放后的高度
BufferedImage ret = resize(srcImage, maxWidth, (int) maxHeight);
save(ret, destImageFile);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Encodes an image in JPEG format and writes it to an output stream.
*
* @param bufferedImage the image to be encoded (<code>null</code> not
* permitted).
* @param outputStream the OutputStream to write the encoded image to
* (<code>null</code> not permitted).
*
* @throws IOException if there is an I/O problem.
* @throws NullPointerException if <code>bufferedImage</code> is
* <code>null</code>.
*/
public void encode(BufferedImage bufferedImage, OutputStream outputStream)
throws IOException {
if (bufferedImage == null) {
throw new IllegalArgumentException("Null 'image' argument.");
}
if (outputStream == null) {
throw new IllegalArgumentException("Null 'outputStream' argument.");
}
Iterator iterator = ImageIO.getImageWritersByFormatName("jpeg");
ImageWriter writer = (ImageWriter) iterator.next();
ImageWriteParam p = writer.getDefaultWriteParam();
p.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
p.setCompressionQuality(this.quality);
ImageOutputStream ios = ImageIO.createImageOutputStream(outputStream);
writer.setOutput(ios);
writer.write(null, new IIOImage(bufferedImage, null, null), p);
ios.flush();
writer.dispose();
ios.close();
}
static void writeImage(
final File file,
final PolygonChromosome chromosome,
final int width,
final int height
) {
final double MIN_SIZE = 500;
final double scale = max(max(MIN_SIZE/width, MIN_SIZE/height), 1.0);
final int w = (int)round(scale*width);
final int h = (int)round(scale*height);
try {
final BufferedImage image = new BufferedImage(w, h, TYPE_INT_ARGB);
final Graphics2D graphics = image.createGraphics();
chromosome.draw(graphics, w, h);
ImageIO.write(image, "png", file);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@Override
public void write(AwtImage image, ImageMetadata metadata, OutputStream out) throws IOException {
javax.imageio.ImageWriter writer = ImageIO.getImageWritersByFormatName("gif").next();
ImageWriteParam params = writer.getDefaultWriteParam();
if (progressive) {
params.setProgressiveMode(ImageWriteParam.MODE_DEFAULT);
} else {
params.setProgressiveMode(ImageWriteParam.MODE_DISABLED);
}
try (MemoryCacheImageOutputStream output = new MemoryCacheImageOutputStream(out)) {
writer.setOutput(output);
writer.write(null, new IIOImage(image.awt(), null, null), params);
writer.dispose();
}
// IOUtils.closeQuietly(out);
}
public Object load(AssetInfo info) throws IOException {
if (ImageIO.getImageWritersBySuffix(info.getKey().getExtension()) != null){
boolean flip = ((TextureKey) info.getKey()).isFlipY();
InputStream in = null;
try {
in = info.openStream();
Image img = load(in, flip);
return img;
} finally {
if (in != null){
in.close();
}
}
}
return null;
}
/**
* return the Transfer Data of type DataFlavor from InputStream
* @param df The DataFlavor.
* @param ins The InputStream corresponding to the data.
* @return The constructed Object.
*/
public Object getTransferData(DataFlavor df, DataSource ds) {
// this is sort of hacky, but will work for the
// sake of testing...
if (df.getMimeType().startsWith("image/jpeg")) {
if (df.getRepresentationClass().getName().equals(STR_SRC)) {
InputStream inputStream = null;
BufferedImage jpegLoadImage = null;
try {
inputStream = ds.getInputStream();
jpegLoadImage = ImageIO.read(inputStream);
} catch (Exception e) {
System.out.println(e);
}
return jpegLoadImage;
}
}
return null;
}
public static void main(String[] args) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
dos.writeInt(1);
dos.writeInt(0x7fffffff);
dos.writeInt(0x8fffffff);
dos.writeInt(0xffffffff);
dos.close();
ByteArrayInputStream bais =
new ByteArrayInputStream(baos.toByteArray());
ImageInputStream iis = ImageIO.createImageInputStream(bais);
for (int i=0; i<4; i++) {
long res = iis.readUnsignedInt();
if (res <= 0) {
throw new RuntimeException("Negative number was read: "+
Long.toString(res, 16));
}
}
}
public static void main(String[] args) throws Exception {
String format = "javax_imageio_1.0";
BufferedImage img =
new BufferedImage(16, 16, BufferedImage.TYPE_INT_RGB);
ImageWriter iw = ImageIO.getImageWritersByMIMEType("image/png").next();
IIOMetadata meta =
iw.getDefaultImageMetadata(new ImageTypeSpecifier(img), null);
DOMImplementationRegistry registry;
registry = DOMImplementationRegistry.newInstance();
DOMImplementation impl = registry.getDOMImplementation("XML 3.0");
Document doc = impl.createDocument(null, format, null);
Element root, text, entry;
root = doc.getDocumentElement();
root.appendChild(text = doc.createElement("Text"));
text.appendChild(entry = doc.createElement("TextEntry"));
// keyword isn't #REQUIRED by the standard metadata format.
// However, it is required by the PNG format, so we include it here.
entry.setAttribute("keyword", "Comment");
entry.setAttribute("value", "Some demo comment");
meta.mergeTree(format, root);
}
/**
* Generates an image of what currently is drawn on the canvas.
* <p/>
* Throws an {@link ActivitiException} when {@link #close()} is already
* called.
*/
public InputStream generateImage(String imageType) {
if (closed) {
throw new ActivitiException("ProcessDiagramGenerator already closed");
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
// Try to remove white space
minX = (minX <= 5) ? 5 : minX;
minY = (minY <= 5) ? 5 : minY;
BufferedImage imageToSerialize = processDiagram;
if (minX >= 0 && minY >= 0) {
imageToSerialize = processDiagram.getSubimage(minX - 5, minY - 5, canvasWidth - minX + 5, canvasHeight - minY + 5);
}
ImageIO.write(imageToSerialize, imageType, out);
} catch (IOException e) {
throw new ActivitiException("Error while generating process image", e);
} finally {
IoUtil.closeSilently(out);
}
return new ByteArrayInputStream(out.toByteArray());
}
private static void plot(Vector vector, int height, int width, String imageFile) throws Exception{
BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
// Graphics2D g2d = image.createGraphics();
// g2d.setBackground(Color.WHITE);
//
//
// g2d.fillRect ( 0, 0, image.getWidth(), image.getHeight() );
// g2d.dispose();
for (int i=0;i<width;i++){
for (int j=0;j<height;j++){
int v = (int)(vector.get(i*width+j));
int rgb = 65536 * v + 256 * v + v;
image.setRGB(j,i,rgb);
// image.setRGB(j,i,(int)(vector.get(i*width+j)/255*16777215));
}
}
new File(imageFile).getParentFile().mkdirs();
ImageIO.write(image,"png",new File(imageFile));
}
/** Creates new form WelcomePanel */
public WelcomePanel() {
initComponents();
setOpaque(true);
welcomeTooltipMap.put(jxHelpLabel, "<html> <h2 style='color:#953333; font-weight: bold;'>Integrierte Hilfe</h2> DS Workbench bietet eine umfangreiche Hilfe, die du im Programm jederzeit über <strong>F1</strong> aufrufen kannst. Dabei wird versucht, das passende Hilfethema für die Ansicht, in der du dich gerade befindest, auszuwählen. Es schadet aber auch nicht, einfach mal so in der Hilfe zu stöbern um neue Funktionen zu entdecken. Einsteiger sollten in jedem Fall die ersten drei Kapitel der Wichtigen Grundlagen gelesen haben.</html>");
welcomeTooltipMap.put(jxCommunityLabel, "<html> <h2 style='color:#953333; font-weight: bold;'>Die DS Workbench Community</h2> Natürlich gibt es neben dir noch eine Vielzahl anderer Spieler, die DS Workbench regelmäßig und intensiv benutzen. Einen perfekten Anlaufpunkt für alle Benutzer bietet das DS Workbench Forum, wo man immer jemanden trifft mit dem man Erfahrungen austauschen und wo man Fragen stellen kann.</html>");
welcomeTooltipMap.put(jxIdeaLabel, "<html> <h2 style='color:#953333; font-weight: bold;'>Verbesserungen und Ideen </h2> Gibt es irgendwas wo du meinst, dass es in DS Workbench fehlt und was anderen Benutzern auch helfen könnte? Hast du eine Idee, wie man DS Workbench verbessern oder die Handhabung vereinfachen könnte? Dann bietet dieser Bereich im DS Workbench Forum die perfekte Anlaufstelle für dich. Trau dich und hilf mit, DS Workbench zu verbessern. </html>");
welcomeTooltipMap.put(jxFacebookLabel, "<html> <h2 style='color:#953333; font-weight: bold;'>DS Workbench @ Facebook</h2> Natürlich gehört es heutzutage fast zum guten Ton, bei Facebook in irgendeiner Art und Weise vertreten zu sein. Auch DS Workbench hat eine eigene Facebook Seite, mit deren Hilfe ihr euch jederzeit über aktuelle News oder Geschehnisse im Zusammenhang mit DS Workbench informieren könnt.</html>");
welcomeTooltipMap.put(jContentLabel, "<html> <h2 style='color:#953333'>Willkommen bei DS Workbench</h2> Wenn du diese Seite siehst, dann hast du DS Workbench erfolgreich installiert und die ersten Schritte ebenso erfolgreich gemeistert. Eigentlich steht nun einer unbeschwerten Angriffsplanung und -durchführung nichts mehr im Wege. Erlaube mir trotzdem kurz auf einige Dinge hinzuweisen, die dir möglicherweise beim <b>Umgang mit DS Workbench helfen</b> oder aber dir die Möglichkeit geben, einen wichtigen Teil zur <b>Weiterentwicklung und stetigen Verbesserung</b> dieses Programms beizutragen. Fahre einfach mit der Maus über eins der vier Symbole in den Ecken, um hilfreiche und interessante Informationen rund um DS Workbench zu erfahren. Klicke auf ein Symbol, um direkt zum entsprechenden Ziel zu gelangen. Die Einträge findest du später auch im Hauptmenü unter 'Sonstiges'. <br> <h3 style='color:#953333'> Nun aber viel Spaß mit DS Workbench.</h3> </html>");
try {
back = ImageIO.read(WelcomePanel.class.getResource("/images/c.gif"));
} catch (Exception ignored) {
}
if (back != null) {
setBackgroundPainter(new MattePainter(new TexturePaint(back, new Rectangle2D.Float(0, 0, 200, 20))));
}
}
/**
* Generates an image of what currently is drawn on the canvas.
* <p/>
* Throws an {@link ActivitiException} when {@link #close()} is already
* called.
*/
public InputStream generateImage(String imageType) {
if (closed) {
throw new ActivitiException("ProcessDiagramGenerator already closed");
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
// Try to remove white space
minX = (minX <= 5) ? 5 : minX;
minY = (minY <= 5) ? 5 : minY;
BufferedImage imageToSerialize = processDiagram;
if (minX >= 0 && minY >= 0) {
imageToSerialize = processDiagram.getSubimage(minX - 5, minY - 5, canvasWidth - minX + 5, canvasHeight - minY + 5);
}
ImageIO.write(imageToSerialize, imageType, out);
} catch (IOException e) {
throw new ActivitiException("Error while generating process image", e);
} finally {
IoUtil.closeSilently(out);
}
return new ByteArrayInputStream(out.toByteArray());
}
/**
* This method is meant to be used for development purpose. In some situations you want to "fake" the readScreen result
* with an hand-crafted image. If this is the case, this method is here to help with it.
*
* @param screenFilePath the path to the image to be used to load the screen
*/
@SuppressWarnings("unused")
void loadScreen(String screenFilePath) {
File screenImgFile = new File(screenFilePath);
if (screenImgFile.exists()) {
BufferedImage screenImg = null;
try {
screenImg = ImageIO.read(screenImgFile);
} catch (IOException e) {
BHBot.logger.error("Error when loading game screen ", e);
}
img = screenImg;
} else {
BHBot.logger.error("Impossible to load screen file: " + screenImgFile.getAbsolutePath());
}
}
public static final Icon createImageIconFromAssets(String imageName, int maxHeight) {
File cacheFile = new File(TMP_ASSETS_ICONS_FILE, imageName);
logger.debug("icon: {}", imageName);
try {
if ( !cacheFile.exists() ) {
downloadImageToFile(cacheFile, ASSETS_ICONS_DIR.concat(imageName));
}
FileInputStream fis = new FileInputStream(cacheFile);
BufferedImage image = ImageIO.read(fis);
int height = image.getHeight();
if ( height > maxHeight ) {
image = GraphicsUtilities.createThumbnail(image, maxHeight);
}
ImageIO.write(image, "png", cacheFile);
ImageIcon icon = new ImageIcon(image);
return icon;
} catch (IOException e) {
logger.warn("Failed to read: {}", cacheFile.getAbsolutePath());
logger.error("Exception", e);
downloadImageToFile(cacheFile, ASSETS_ICONS_DIR.concat(imageName));
}
MissingIcon imageIcon = new MissingIcon();
return imageIcon;
}
/**
* Checks an image color. RED and GREEN are allowed only.
*/
private static void checkColors(final BufferedImage bi1,
final BufferedImage bi2)
throws IOException {
for (int i = 0; i < SIZE; ++i) {
for (int j = 0; j < SIZE; ++j) {
final int rgb1 = bi1.getRGB(i, j);
final int rgb2 = bi2.getRGB(i, j);
if (rgb1 != rgb2 || rgb1 != 0xFFFF0000 && rgb1 != 0xFF00FF00) {
ImageIO.write(bi1, "png", new File("image1.png"));
ImageIO.write(bi2, "png", new File("image2.png"));
throw new RuntimeException("Failed: wrong text location");
}
}
}
}
public void run() {
// System.out.println("Thread " + threadName + " in thread group " +
// getThreadGroup().getName());
// Create a new AppContext as though we were an applet
SunToolkit.createNewAppContext();
// Get default registry and store reference
this.registry = IIORegistry.getDefaultInstance();
for (int i = 0; i < 10; i++) {
// System.out.println(threadName +
// ": setting cache parameters to " +
// useCache + ", " + cacheDirectory);
ImageIO.setUseCache(useCache);
ImageIO.setCacheDirectory(cacheDirectory);
try {
sleep(1000L);
} catch (InterruptedException e) {
}
// System.out.println(threadName + ": reading cache parameters");
boolean newUseCache = ImageIO.getUseCache();
File newCacheDirectory = ImageIO.getCacheDirectory();
if (newUseCache != useCache ||
newCacheDirectory != cacheDirectory) {
// System.out.println(threadName + ": got " +
// newUseCache + ", " +
// newCacheDirectory);
// System.out.println(threadName + ": crosstalk encountered!");
gotCrosstalk = true;
}
}
}
public void takeSnapShot(OutputStream output)
{
JavaFxRunnable worker = new JavaFxRunnable()
{
public void myWork()
throws Exception
{
Scene scene = console.getConsoleScene();
WritableImage writableImage =
new WritableImage((int)scene.getWidth(), (int)scene.getHeight());
scene.snapshot(writableImage);
try
{
ImageIO.write(SwingFXUtils.fromFXImage(writableImage, null), "png", output);
}
catch (IOException ex)
{
log.error( "Snapshot failed with: ", ex );
}
}
};
Platform.runLater( worker );
worker.doWait();
}
private ActionListener addPictureListener() {
final ActionListener listener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser sec = new JFileChooser();
FileNameExtensionFilter JpegFilter = new FileNameExtensionFilter("JPG & GIF & PNG Images", "jpg", "gif", "png");
sec.setFileFilter(JpegFilter);
sec.setAcceptAllFileFilterUsed(false);
sec.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
int result = sec.showOpenDialog(sec);
if (result == JFileChooser.APPROVE_OPTION) {
try {
newImage = ImageIO.read(sec.getSelectedFile());
final int pictureWidth = 586;
final int pictureHeight = 218;
BufferedImage hotelPicture = new BufferedImage(pictureWidth, pictureHeight, newImage.getType());
Graphics2D g = hotelPicture.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(newImage, 0, 0, pictureHeight, pictureHeight, null);
g.dispose();
pictlabel.setIcon(new ImageIcon(hotelPicture));
pictlabel.revalidate();
pictlabel.repaint();
} catch (IOException e1) {
JOptionPane.showMessageDialog(modalFrame, "Image cannot be null !",
JOptionPane.MESSAGE_PROPERTY, JOptionPane.WARNING_MESSAGE);
}
}
}
};
return listener;
}
public Image[] loadImages(String path) {
File f = new File(path);
if (path.toUpperCase().endsWith(".ICO")) {
//
// Try to load with our ico codec...
//
try {
java.awt.Image[] images = net.charabia.util.codec.IcoCodec.loadImages(f);
if ((images != null) && (images.length > 0)) {
return images;
}
} catch (java.io.IOException exc) {
exc.printStackTrace();
}
}
//
// defaults to the standard java loading process
//
BufferedImage bufferedImage;
try {
bufferedImage = ImageIO.read(f);
javax.swing.ImageIcon icon = new javax.swing.ImageIcon(bufferedImage, "default icon");
java.awt.Image[] imgs = new java.awt.Image[1];
imgs[0] = icon.getImage();
return imgs;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static BufferedImage loadImage(String path){
try {
return ImageIO.read(ImageLoader.class.getResource(path));
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
return null;
}
/**
* As {@link #writeToStream(BitMatrix, String, OutputStream)}, but allows customization of the output.
*/
public static void writeToStream(BitMatrix matrix, String format, OutputStream stream, MatrixToImageConfig config)
throws IOException {
BufferedImage image = toBufferedImage(matrix, config);
if (!ImageIO.write(image, format, stream)) {
throw new IOException("Could not write an image of format " + format);
}
}
public void beginDecoding() {
// Initialize the JPEG reader if needed.
if(this.JPEGReader == null) {
// Get all JPEG readers.
Iterator<ImageReader> iter = ImageIO.getImageReadersByFormatName("jpeg");
if(!iter.hasNext()) {
throw new IllegalStateException("No JPEG readers found!");
}
// Initialize reader to the first one.
this.JPEGReader = iter.next();
this.JPEGParam = JPEGReader.getDefaultReadParam();
}
// Get the JPEGTables field.
TIFFImageMetadata tmetadata = (TIFFImageMetadata)metadata;
TIFFField f =
tmetadata.getTIFFField(BaselineTIFFTagSet.TAG_JPEG_TABLES);
if (f != null) {
this.hasJPEGTables = true;
this.tables = f.getAsBytes();
} else {
this.hasJPEGTables = false;
}
}
private static void verify(BufferedImage bi) throws IOException {
for (int i = 0; i < SIZE; ++i) {
for (int j = 0; j < 99; ++j) {
//Text should not appear before 100
if (bi.getRGB(i, j) != Color.RED.getRGB()) {
ImageIO.write(bi, "png", new File("image.png"));
throw new RuntimeException("Failed: wrong text location");
}
}
}
}