Tinify API with Android - java

Is it possible to use tinify compression API in Android? I've implemented all the required stuff, but the app is crashing all the time. Here's the code:
File photo = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), imageName()+".jpg");
try {
Log.d("TINY", photo.getAbsolutePath());
Source source = Tinify.fromFile(photo.getAbsolutePath());
} catch (IOException e) {
Log.e("TINY", e.getMessage());
e.printStackTrace();
}
A am getting the following error:
FATAL EXCEPTION: main
java.lang.NoClassDefFoundError: java.nio.file.Paths
If it's not possible, are there any other good APIs for image compression for Android?

It's not possible as-is. Note that java.nio.file.Paths was added in Java 7, but Android still only fully supports Java 6, with some Java 7 language features if you are using a specific buildToolsVersion and minSdkVersion. Also see the Things that don't Work section at the Java7-on-Android project page.

Like the answer to Android import java.nio.file.Files; cannot be resolved states, it's not possible to use classes from the java.nio.file package.
But that doesn't necessarily mean you can't use the Tinify API. If you're able to provide all other referenced classes, you can use it with a few modifications, since it's open source and there are only two occurrences of Files and Paths you need to rewrite:
Result.java
public void toFile(final String path) throws IOException {
Files.write(Paths.get(path), toBuffer());
}
Source.java
public static Source fromFile(final String path) throws IOException {
return fromBuffer(Files.readAllBytes(Paths.get(path)));
}

Related

CodenameOne Java String.Format "error: cannot find symbol" on Hello World example

A super-simple String.format("this is a test %d",5) doesn't work in my HelloWorld CodenameOne project: I get "error: cannot find symbol".
It doesn't seem to matter what format I used, I always get the same error. This seems to be an import problem, though I'm not importing any special packages outside of the defaults.
Here is the java source:
package com.test.test;
import static com.codename1.ui.CN.*;
import com.codename1.ui.Display;
import com.codename1.ui.Form;
import com.codename1.ui.Dialog;
import com.codename1.ui.Label;
import com.codename1.ui.plaf.UIManager;
import com.codename1.ui.util.Resources;
import com.codename1.io.Log;
import com.codename1.ui.Toolbar;
import java.io.IOException;
import com.codename1.ui.layouts.BoxLayout;
import com.codename1.io.NetworkEvent;
/**
* This file was generated by Codename One for the purpose
* of building native mobile applications using Java.
*/
public class MyApplication {
private Form current;
private Resources theme;
public void init(Object context) {
// use two network threads instead of one
updateNetworkThreadCount(2);
theme = UIManager.initFirstTheme("/theme");
// Enable Toolbar on all Forms by default
Toolbar.setGlobalToolbar(true);
// Pro only feature
Log.bindCrashProtection(true);
/*
Updating property file: C:\Users\admin\Desktop\test2\build\built-jar.properties
Compile is forcing compliance to the supported API's/features for maximum device compatibility. This allows smaller
code size and wider device support
Compiling 1 source file to C:\Users\admin\Desktop\test2\build\tmp
C:\Users\admin\Desktop\test2\src\com\test\test\MyApplication.java:39: error: cannot find symbol
s = String.format("this is a test %d",5);
symbol: method format(String,int)
location: class String
1 error
C:\Users\admin\Desktop\test2\build.xml:62: Compile failed; see the compiler error output for details.
BUILD FAILED (total time: 0 seconds)
*/
String s;
s = String.format("this is a test %d",5);
addNetworkErrorListener(err -> {
// prevent the event from propagating
err.consume();
if(err.getError() != null) {
Log.e(err.getError());
}
Log.sendLogAsync();
Dialog.show("Connection Error", "There was a networking error in the connection to " + err.getConnectionRequest().getUrl(), "OK", null);
});
}
public void start() {
if(current != null){
current.show();
return;
}
Form hi = new Form("Hi World", BoxLayout.y());
hi.add(new Label("Hi World"));
hi.show();
}
public void stop() {
current = getCurrentForm();
if(current instanceof Dialog) {
((Dialog)current).dispose();
current = getCurrentForm();
}
}
public void destroy() {
}
}
CodenameOne compiles your source code using its own subset of the Java SE API, which is missing some features that the standard Java API includes.
Quoting their FAQ:
What features of Java are supported? What features of Java aren't supported?
The most obvious thing missing is reflections. The main problem is that when we package the VM into devices that don’t have Java, we would have to include EVERYTHING. If reflections were included, they wouldn’t work anyway since we obfuscate the code for the platforms where reflections do work (e.g. Android). On top of that reflection code is generally slow and a bad idea on a mobile device to begin with. As an alternative some developers were successful with bytecode manipulation which is something that is completely seamless to the server and as performant/efficient as handcoding.
Many of the desktop API’s such as java.net, java.io.File etc. aren’t very appropriate for mobile devices and just didn’t make it. We provide our own alternatives which are more portable and better suited for mobile settings.
Of the other missing things, if you run into a missing method or ability, there are cases where that functionality can be added.
Specifically, its version of java.lang.String does not include the format method.
In this case, it can be rewritten using simple string concatenation:
String s = "this is a test " + 5;

OCR Logger Could Not be Resolved-Java

So I am trying to get an OCR working for a bigger project that reads characters from an image and I am following this you tube video: https://www.youtube.com/watch?v=aEMSxiXctPk
I did everything in the video and still cannot get it to work. I looked on this forum about the error I am getting, but it looks like their projects are different so I think they need different jars than I would. I have all of the jars from the video or at least I think I do. Any ways, the issue in java delivered this message.
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The type org.slf4j.Logger cannot be resolved. It is indirectly referenced from required .class files
org.slf4j.Logger cannot be resolved to a type
LoggerFactory cannot be resolved
The method setDatapath(String) of type Tesseract must override a superclass method
This is my code:
package Tess4j;
import java.io.*;
import net.sourceforge.tess4j.*;
import org.slf4j.*;
public class test {
public static void main(String[] args) throws IOException{
File imageFile = new File("C:\\Users\\Sean\\workspace\\Bigno Tracker\\Images\\eurotext.png");
ITesseract instance=new Tesseract();
instance.setDatapath("C:\\Users\\Sean\\workspace\\Bigno Tracker\\tessdata");
try {
String result=instance.doOCR(imageFile);
System.out.println(result);
}catch (TesseractException e) {
System.err.println(e.getMessage());
}
}
}
This is an image of my screen that shows the jars I have.
So what am I missing?
Thanks in advance.
Edit:
I don’t really understand your question but, I’ve done some work with OCR Engines in the past.. ABBYY hass a good one that’s really easy to integrate!
P.S Did a little research, check to see if you have all the appropriate dependencies for your OCR engine version
Cheers

JAVA NoClassDefFoundError on external jar library

I'm writing an Android app in JAVA using this library for formatting phone numbers.
I am receiving the following exception:
java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/i18n/phonenumbers/PhoneNumberUtil;
Here:
public class InvocationTargetException extends ReflectiveOperationException {
...
public InvocationTargetException(Throwable exception) {
super(null, exception);
target = exception;
}
...
}
When executing the command:
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
I have imported the com.google.i18n.phonenumbers lib, but I cant figure out what is the L in the exception description.
L is added for internal JVM objectype representation, but it is actually looking for com/google/i18n/phonenumbers/PhoneNumberUtil class.
It seems the library is missing in your Runtime classpath.
Field Descriptions Documentation.
Did you add the jar file to your class path? Are you using Android Studio? In that case you can add the entry to the app/build.gradle file.

Add Java SE Classes to Java ME read PDF

I'm writing a Java ME application that uses iText to read PDF. When I write my code in standard Java including the iText libraries in the class-path, the application runs. However if I move the code into a java mobile application including the iText libraries in the class-path there is an error during compiling that says
error: cannot access URL
PdfReader reader = new PdfReader(pdfPath);
class file for java.net.URL not found
My problem is that I need a work around to read the PDF file. I've tried adding rt.jar as a library into my code which is the package that contains java.io but it is too big to be compiled. Please help me find a work around. My code is here
package PDFreaderpackage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;
import com.sun.lwuit.Display;
import com.sun.lwuit.Form;
import com.sun.lwuit.TextArea;
import javax.microedition.midlet.MIDlet;
public class Midlet extends MIDlet {
Form displayForm;
TextArea pdfText;
private String bookcontent;
public static String INPUTFILE = "c:/test.pdf";
public static int pageNumber = 1;
public void startApp() {
Display.init(this);
this.bookcontent = readPDF(INPUTFILE, pageNumber);
pdfText = new TextArea(bookcontent);
displayForm = new Form("Works");
displayForm.addComponent(pdfText);
displayForm.show();
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public String readPDF(String pdfPath, int pageNumber) {
try {
PdfReader reader = new PdfReader(pdfPath);
this.bookcontent = PdfTextExtractor.getTextFromPage(reader, pageNumber);
} catch (Exception e) {
System.out.println(e);
}
return bookcontent;
}
}
These classes aren't available on a mobile device and JavaME doesn't support Java 5 features. What you are trying to do is somewhat impractical. Codename One allows some more classes thanks to bytecode processing but even then this isn't close to a complete rt.jar.
If you have the time, you can try and create a Java ME compliant version of iText, but to properly open a PDF the library must use some form of Random Access File because of the xref table at the end of the file. This sort of file connection is not available in Java ME.
What the library can do is to fully load the PDF to memory, which is highly dependent on the file size and the handset memory available.
You better create a Web Service to receive your PDF and return, for example, PNG images from it.

Is it possible with Java to delete to the Recycle Bin?

Java is the key here. I need to be able to delete files but users expect to be able to "undelete" from the recycle bin. As far as I can tell this isn't possible. Anyone know otherwise?
Ten years later, with Java 9, finally there is a builtin way to move files to the Trash Bin
java.awt.Desktop.moveToTrash(java.io.File):
public boolean moveToTrash​(File file)
Moves the specified file to the trash.
Parameters:
file - the file
Returns:
returns true if successfully moved the file to the trash.
The availability of this feature for the underlying platform can be tested with Desktop.isSupported​(Desktop.Action.MOVE_TO_TRASH).
For various reasons Windows has no concept of a folder that simply corresponds to the Recycle Bin.
The correct way is to use JNI to invoke the Windows SHFileOperation API, setting the FO_DELETE flag in the SHFILEOPSTRUCT structure.
SHFileOperation documention
Java example for copying a file using SHFileOperation (the Recycle Bin link in the same article doesn't work)
Java 9 has new method but in my case I am restricted to Java 8.
I found Java Native Access Platform that has hasTrash() and moveToTrash() method. I tested it on Win 10 and Mac OS (Worked) for me.
static boolean moveToTrash(String filePath) {
File file = new File(filePath);
FileUtils fileUtils = FileUtils.getInstance();
if (fileUtils.hasTrash()) {
try {
fileUtils.moveToTrash(new File[] { file });
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
} else {
System.out.println("No Trash");
return false;
}
}
Maven Repository
https://mvnrepository.com/artifact/net.java.dev.jna/jna-platform/5.1.0
Don't confuse It is Java Native Access Platform not Java Native Access
See the fileutil incubator project (part of the Java Desktop Integration Components project):
This incubator project is created to host those file utility functionalities, most of which are extensions to the java.io.File class in J2SE. There are frequent requests from Java developers for such features like: sending a file to trash bin, checking free disk space, accessing file attributes etc. This project addresses such frequently requested APIs.
Note, this should work not only on Windows, but on other platforms (Linux, Mac OS X) as well.
My 3 cents - use cmd util Recycle.exe with -f to force recycle (no prompt). Works perfectly.
public class Trash {
public void moveToTrash(File ... file) throws IOException {
moveToTrash(false, file);
}
public void promptMoveToTrash(File ... file) throws IOException {
moveToTrash(true, file);
}
private void moveToTrash(boolean withPrompt, File ... file) throws IOException {
String fileList = Stream.of(file).map(File::getAbsolutePath).reduce((f1, f2)->f1+" "+f2).orElse("");
Runtime.getRuntime().exec("Recycle.exe "+(withPrompt ? "" : "-f ")+fileList);
}
}
In JNA platform, the FileUtils doesn't use Win32 API. You should prefer W32FileUtils which supports Undo (restore the file from recycle bin).
Edit: as of the current version of JNA Platform (5.7.0), with FileUtils.getInstance(), this statement has become incorrect, and FileUtils will use the Win32 API.

Categories