Skip to content

Instantly share code, notes, and snippets.

@ed-george
Created May 26, 2015 14:52
Show Gist options
  • Save ed-george/2068c53b6d7fe9be9369 to your computer and use it in GitHub Desktop.
Save ed-george/2068c53b6d7fe9be9369 to your computer and use it in GitHub Desktop.
Image compression script using online service - TinyPNG
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.io.File;
import javax.xml.bind.DatatypeConverter;
public class OptimizeImage {
private static final String API_URL = "https://api.tinify.com/shrink";
private static int count = 0;
private static final String output = "output.png";
private static long initialSize = 0;
public static void main(String[] args) throws Exception {
if(args.length < 1){
System.err.println("Not enough arguments");
return;
}
final String input = args[0];
checkInput(input);
loop(input);
}
public static void checkInput(String input){
File inputFile = new File(input);
if(!inputFile.exists()){
System.err.println("File doesnt exist");
System.exit(1);
}
initialSize = inputFile.length();
System.out.println("Initial size: " + size);
}
public static void loop(String input) throws Exception {
final String key = "api-key-here";
HttpURLConnection connection = (HttpURLConnection) new URL(API_URL).openConnection();
String auth = DatatypeConverter.printBase64Binary(("api:" + key).getBytes("UTF-8"));
connection.setRequestProperty("Authorization", "Basic " + auth);
connection.setDoOutput(true);
try (OutputStream request = connection.getOutputStream()) {
Files.copy(Paths.get(input), request);
}
if (connection.getResponseCode() == 201) {
// Compression was successful, retrieve output from Location header.
final String url = connection.getHeaderFields().get("Location").get(0);
connection = (HttpURLConnection) new URL(url).openConnection();
try (InputStream response = connection.getInputStream()) {
Files.copy(response, Paths.get(output), StandardCopyOption.REPLACE_EXISTING);
}
long size = new File(output).length();
System.out.println("Size: " + size);
if(count < 4){
count++;
System.out.println("Completed cycle " + count);
loop(output);
}else{
long diff = initialSize - size;
System.out.println("Final compression - removed " + diff + " bytes");
}
} else {
// Something went wrong! You can parse the JSON body for details.
System.err.println("Compression failed.");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment