Converting images from .bmp to jpeg2000 on java and eclipse error - java

I have seen some examples here and installed Java Advanced Imaging Image I/O Tools on my computer, because obviously it is a requirement of processing JPEG2000 images.
After install this i am able to import libraries
e.g.
import com.sun.media.imageio.plugins.*;
after importing, i should be able to use constructors or methods of that library but i am getting this error:
"Access restriction: The type 'J2KImageWriteParam' is not API (restriction on required library 'C:\Program Files (x86)\Java\jre1.8.0_77\lib\ext\jai_imageio.jar')"
After a litle bit research, i found out that i can change eclipse preferences and ignore that error.
I went through this way: Preferences -> Java -> Compiler -> Errors / Warnings -> Deprecated and Restricted API. Then i changed errors to warnings. But now i can not use that library efficient, cause eclipse suggest me nothing about that library.
My first question is; if there is a better way to do that? Or maybe another way to use this library efficient in eclipse?
EDIT: I found out it was a complication of 32 and 64 bit versions. After installing 32bit JDK and reference the jai_imageio.jar it worked fine.
And second; Can anybody give a plain example to me about converting .bmp image to jpeg2000 image. That would help a lot to me about undesrtanding the context.
Thank you

You need to have these in your imports:
import javax.imageio.*;
import javax.imageio.stream.*;
import com.sun.media.imageio.plugins.jpeg2000.*;
import com.sun.media.imageio.stream.*;
and these jars
jai_imageio.jar;jai_codec.jar;jai_core.jar
This is an example that runs fine for me - but dont know if the produced j2k are valid or anything - use your j2000 viewer to check that.
public void toJ2000(String inputFile, String outputFile) throws IOException {
J2KImageWriteParam iwp = new J2KImageWriteParam();
FileInputStream fis = new FileInputStream(new File(inputFile));
BufferedImage image = ImageIO.read(fis);
fis.close();
if (image == null)
{
System.out.println("If no registered ImageReader claims to be able to read the resulting stream");
}
Iterator writers = ImageIO.getImageWritersByFormatName("JPEG2000");
String name = null;
ImageWriter writer = null;
while (name != "com.sun.media.imageioimpl.plugins.jpeg2000.J2KImageWriter") {
writer = (ImageWriter) writers.next();
name = writer.getClass().getName();
System.out.println(name);
}
File f = new File(outputFile);
long s = System.currentTimeMillis();
ImageOutputStream ios = ImageIO.createImageOutputStream(f);
writer.setOutput(ios);
J2KImageWriteParam param = (J2KImageWriteParam) writer.getDefaultWriteParam();
IIOImage ioimage = new IIOImage(image, null, null);
writer.write(null, ioimage, param);
System.out.println(System.currentTimeMillis() - s);
writer.dispose();
ios.flush();
ios.close();
image.flush();
}
public static void main(String[] args) {
TR t=new TR();
try {
t.toJ2000("yel.png", "yel.j2k");
}
catch (Exception ex) { ex.printStackTrace(); }
}

Related

How to write a Zip File with the "DFLT-X" Method

I am working on a Software which bundles and exports XML files as a zip. The compression method is "Deflate" (Code snipped included below).
These zip files are needed in another (older) Software, which is build up on "QT" (Code snipped also below).
The Problem is, that the zip files are not accepted in the second Software. If these zip files get rezipped manually, they work suddendly.
To find any differences in the generated zip and the Manual one, i plugged both into "powerArchiver" and saw they are exactly the same except for the "Method", which is "DFLT-X" on the workign zip and "DFLT-N" on the not working one (Note: working refers to the second Software import, both zip files can be extracted without Problems manually).
Any ideas how i can get the "DFLT-X" Method with Java utils libs?
I tried all settings and variants (.setLevel(), setMethod()) for "ZipOutputStream", "Deflater" and "DeflaterOutputStream" but i only got the "DFLT-N" Format.
The Explanation what these Formats are is not included in the powerArchiver Forums or else where. "DFLT-N" seems to refer to "Deflate, Normal" and the X variant for some higher compression, but not Deflate64.
Software 1, generating the zip:
final byte[] buffer = new byte[1024];
FileOutputStream fos = null;
ZipOutputStream zos = null;
try {
fos = new FileOutputStream(zipFile);
zos = new ZipOutputStream(fos);
FileInputStream inputStream = null;
for (final String file : this.fileList) {
if (file.toString().contains(".xml")) {
final ZipEntry ze = new ZipEntry(File.separator + file);
zos.putNextEntry(ze);
try {
inputStream = new FileInputStream(sourceFolder + File.separator + file);
int len;
while ((len = inputStream.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
}
finally {
if (inputStream != null) {
inputStream.close();
}
}
}
}
zos.closeEntry();
}
catch (final IOException ex) {
ex.printStackTrace();
}
Software 2, reading the zip:
bool WfControlDataStorage::load(const QString& identifier, QByteArray& outZipFileContent) const
{
QFile dataFile(identifierToFilepath(identifier));
if(dataFile.open(QFile::ReadOnly)) {
outZipFileContent = dataFile.readAll();
dataFile.close();
return true;
}
return false;
}
#Holger Thank you for your Time, sounds like you did exactly what i did too.
Solution:
in my Project the zip Entry name had a leading "/" like "/someName". This was not visible in powerarchiver and also didnt hinder decompressing, but my recieving software had troubles resolving this name.
Repacking with powerarchiver removed that slash, so a bunch of undocumented behavior made my life hell.
In Terms of DFLT-X and DFLT-N, these are strange powerarchiver specific namings and i still cannot say how they determine the difference. But i can say, that deflate has no different "methods" nexto the simple levels from 0-9 and the "Deflate64" which is basically never used and obsolete. The DFLT-X naming is unrelated to both and imho completly irrelevant.

Java native file not found, when native file is clearly in java.library.path

I am working on a LWJGL project, and I cannot get the native libraries to work. I can run it in the IDE just fine, but when I export it, it crashes. But here is the problem, I made a bit of code to extract the native files from the Jar, and into a temporary folder, once that is done, it attempts to load the native, but it gives this error:
java.lang.UnsatisfiedLinkError: no jinput-dx8 in java.library.path
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1867)
at java.lang.Runtime.loadLibrary0(Runtime.java:870)
at java.lang.System.loadLibrary(System.java:1122)
at com.test.opengl.engineTester.NativeSupport.loadDLL(NativeSupport.java:46)
at com.test.opengl.engineTester.NativeSupport.extract(NativeSupport.java:23)
at com.test.opengl.engineTester.MainGameLoop.<clinit>(MainGameLoop.java:21)
NativeSupport.class:
import java.io.*;
import java.util.Date;
public class NativeSupport {
private static File tempLocation;
public static void extract() {
tempLocation = new File(System.getProperty("java.io.tmpdir") + "/OpenGL_Test_" + new Date().getTime() + "/");
tempLocation.deleteOnExit();
tempLocation.mkdirs();
System.out.println(System.getProperty("java.library.path"));
String path = tempLocation.getAbsolutePath()+"\\;";
System.setProperty("java.library.path", path);
System.out.println(path);
loadDLL("jinput-dx8.dll");
loadDLL("jinput-dx8_64.dll");
loadDLL("jinput-raw.dll");
loadDLL("jinput-raw_64.dll");
loadDLL("lwjgl.dll");
loadDLL("lwjgl64.dll");
loadDLL("OpenAL32.dll");
loadDLL("OpenAL64.dll");
}
private static void loadDLL(String name) {
try {
System.out.println(name);
BufferedReader in = new BufferedReader(new InputStreamReader(Class.class.getResourceAsStream("/"+name)));
File fileOut = new File(tempLocation, name);
System.out.println(fileOut.getAbsolutePath());
FileWriter out = new FileWriter(fileOut);
char[] buffer = new char[1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
out.close();
System.loadLibrary(fileOut.getName().substring(0, fileOut.getName().length()-4)); // Here is where the crash happens
} catch (Exception e) {
e.printStackTrace();
}
}
public static void clean() {
}
}
The extract method is called in a static call from MainGameLoop.class. I have tried calling it in the main function, and it did the same thing. I also made sure that the files existed before they were loaded.
I would like to avoid the Jar Splice program.
If I was unclear about anything, I will be back with this question in about a day to tidy up my question (I am up at 03:00 trying to solve this problem)
Thanks for your help, I really appreciate it.
Some time ago I have developed sample code that can help you here. Take a look here:
https://github.com/mkowsiak/jnicookbook/tree/master/recipes/recipeNo031
You can find there few components:
library extractor (it takes care for getting native code from jar file)
HelloWorld class that uses arbitrary located native file
Main class that takes care of everything
In your case, I'd use System.load instead of System.loadLibrary. You have the file anyway on your file system.
Have fun with JNI.
For more samples related to JNI, take a look here: http://jnicookbook.owsiak.org

Read Tiff format in Java eclipse

How do i read a TIFF image using Java IMAGEIO library??(I am using Eclipse Luna)..And once i download the plugin(JAR files) how to give the Classpath so that it can read my input TIFF image file?
Here a quick example to convert a TIFF image into a PNG image.
// quick conversion example
File inputFile = new File("image.tiff");
File outputFile = new File("output.png");
BufferedImage image = ImageIO.read(inputFile);
ImageIO.write(image, "png", outputFile);
Print a list of all supported formats of the JAI ImageIO library.
import javax.imageio.ImageIO;
...
for (String format : ImageIO.getWriterFormatNames()) {
System.out.println("format = " + format);
}
note For the convertion of image formats which have no built-in support a supporting library must be in the classpath. To find the supported formats check https://docs.oracle.com/javase/tutorial/2d/images/loadimage.html or the snippet above.
e.g. for TIFF you could use the jai_imageio-1.1.jar (or newer).
javac -cp jai_imageio-1.1.jar:. Main.java
java -cp jai_imageio-1.1.jar:. Main
If no TIFF format supporting library is in the classpath the above convertion snippet fails with java.lang.IllegalArgumentException: image == null!.
Following formats have built-in support (Java 8)
BMP
GIF
JPEG
PNG
WBMP
jai_imageio-1.1.jar adds support for
JPEG2000
PNM
RAW
TIFF
edit As times goes by and Java 9 is released, a small update, because Java 9 supports TIFF now out of the box.
compile and run with Java 9 without an additional library
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
class TiffToPng {
public static void main(String[] args) throws Exception {
File inputFile = new File("image.tiff");
File outputFile = new File("output.png");
BufferedImage image = ImageIO.read(inputFile);
ImageIO.write(image, "png", outputFile);
}
}
to find supported ImageReader / ImageWriter formats resp. MIME types you could use following snippets
for (String format : ImageIO.getReaderFormatNames()) {
System.out.println("format = " + format);
}
...
for (String format : ImageIO.getReaderMIMETypes()) {
System.out.println("format = " + format);
}
for (String format : ImageIO.getWriterFormatNames()) {
System.out.println("format = " + format);
}
...
for (String format : ImageIO.getWriterMIMETypes()) {
System.out.println("format = " + format);
}
If you are getting the error:
java.lang.IllegalArgumentException: image == null!
Just put the below jar :-
If you are using eclipse, just add it to referenced libraries.
If you are using just simple java file and running it through console, just paste this jar in the class path.
jai_imageio-1.1.jar |
http://www.java2s.com/Code/JarDownload/jai/jai_imageio-1.1.jar.zip
And Import the following :
import com.sun.media.imageio.plugins.tiff.*;

How to write images, swf's, videos and anything else that is stored on a website to a file on my computer using streams

I'm trying to write a program that copies a website to my harddrive. This is easy enough to do just copying over the source and saving it as an html file, but In doing that you can't access any of the pictures, videos etc offline. I was wondering if there is a way to do this using an input/output stream and if so how exactly to do it...
Thanks so much in advance
If you have URL of the file to be downloaded then you can simply do it using apache commons-io
org.apache.commons.io.FileUtils.copyURLToFile(URL, File);
EDIT :
This code will download a zip file on your desktop.
import static org.apache.commons.io.FileUtils.copyURLToFile;
public static void Download() {
URL dl = null;
File fl = null;
try {
fl = new File(System.getProperty("user.home").replace("\\", "/") + "/Desktop/Screenshots.zip");
dl = new URL("http://example.com/uploads/Screenshots.zip");
copyURLToFile(dl, fl);
} catch (Exception e) {
System.out.println(e);
}
}

Load and display all the images from a folder

I want to read all the images in a folder using Java.
When: I press a button in the Java application,
It should:
ask for the directory's path in a popup,
then load all the images from this directory,
then display their names, dimension types and size.
How to proceed?
I have the code for read the image and also for all image in the folder but how the things i told above can be done?
Any suggestion or help is welcome! Please provide reference links!
Untested because not on a machine with a JDK installed, so bear with me, that's all typed-in "as-is", but should get you started (expect a rush of downvotes...)
Loading all the Images from a Folder
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Test {
// File representing the folder that you select using a FileChooser
static final File dir = new File("PATH_TO_YOUR_DIRECTORY");
// array of supported extensions (use a List if you prefer)
static final String[] EXTENSIONS = new String[]{
"gif", "png", "bmp" // and other formats you need
};
// filter to identify images based on their extensions
static final FilenameFilter IMAGE_FILTER = new FilenameFilter() {
#Override
public boolean accept(final File dir, final String name) {
for (final String ext : EXTENSIONS) {
if (name.endsWith("." + ext)) {
return (true);
}
}
return (false);
}
};
public static void main(String[] args) {
if (dir.isDirectory()) { // make sure it's a directory
for (final File f : dir.listFiles(IMAGE_FILTER)) {
BufferedImage img = null;
try {
img = ImageIO.read(f);
// you probably want something more involved here
// to display in your UI
System.out.println("image: " + f.getName());
System.out.println(" width : " + img.getWidth());
System.out.println(" height: " + img.getHeight());
System.out.println(" size : " + f.length());
} catch (final IOException e) {
// handle errors here
}
}
}
}
}
APIs Used
This is relatively simple to do and uses only standard JDK-packaged classes:
File
FilenameFilter
BufferedImage
ImageIO
These sessions of the Java Tutorial might help you as well:
Reading/Loading an Image
How to Use Icons
How to Use File Choosers
Possible Enhancements
Use Apache Commons FilenameUtils to extract files' extensions
Detect files based on actual mime-types or content, not based on extensions
I leave UI code up to you. As I'm unaware if this is homework or not, I don't want to provide a full solution. But to continue:
Look at a FileChooser to select the folder.
I assume you already know how to make frames/windows/dialogs.
Read the Java Tutorial How to Use Icons sections, which teaches you how to display and label them.
I left out some issues to be dealt with:
Exception handling
Folders with evil endigs (say you have a folder "TryMeIAmEvil.png")
By combining all of the above, it's pretty easy to do.
javaxt.io.Directory directory = new javaxt.io.Directory("C:\Users\Public\Pictures\Sample Pictures");
directory.getFiles();
javaxt.io.File[] files;
java.io.FileFilter filter = file -> !file.isHidden() && (file.isDirectory() || (file.getName().endsWith(".jpg")));
files = directory.getFiles(filter, true);
System.out.println(Arrays.toString(files));
step 1=first of all make a folder out of webapps
step2= write code to uploading a image in ur folder
step3=write a code to display a image in ur respective jsp,html,jframe what u want
this is folder=(images)
reading image for folder'
Image image = null;
try {
File sourceimage = new File("D:\\images\\slide4.jpg");
image = ImageIO.read(sourceimage);
} catch (IOException e) {
e.printStackTrace();
}
}

Categories

Resources