From 0a9c5f660472715f0561cd0f54ed236d1a6e4805 Mon Sep 17 00:00:00 2001 From: Peter Hellberg Date: Fri, 2 Jan 2015 11:34:21 +0100 Subject: [PATCH] Allow compression of JPEG files (Via TinyJPG) --- README.md | 2 ++ tinypng/main.go | 33 ++++++++++++++++++++++++++++++--- 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 5906af0..f4ceee9 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,8 @@ Then you can run the command: If only the input filename was specified, then the output filename will be `tiny-` +You can also compress JPEG files. + ## License (MIT) Copyright (c) 2014 [Peter Hellberg](http://c7.se/) diff --git a/tinypng/main.go b/tinypng/main.go index c3119c0..3ab1aec 100644 --- a/tinypng/main.go +++ b/tinypng/main.go @@ -21,12 +21,15 @@ Then you can run the command: If only the input filename was specified, then the output filename will be 'tiny-' +You can also compress JPEG files. + */ package main import ( "errors" "fmt" + "image/jpeg" "image/png" "os" "path" @@ -43,9 +46,9 @@ func main() { fatalError("Input file does not exist.") } - // Verify that the input file is a PNG file - if !validPNGFile(inputFilename) { - fatalError("Input file is not a valid PNG file.") + // Verify that the input file is a PNG or JPEG file + if !validFileType(inputFilename) { + fatalError("Input file is not a valid PNG or JPEG file.") } // Then make sure that the output file doesn’t exist @@ -115,6 +118,12 @@ func fileExists(name string) bool { return true } +// Valid file type + +func validFileType(fn string) bool { + return validPNGFile(fn) || validJPEGFile(fn) +} + // PNG func validPNGFile(fn string) bool { @@ -133,6 +142,24 @@ func validPNGFile(fn string) bool { return true } +// JPEG + +func validJPEGFile(fn string) bool { + jpegImage, err := os.Open(fn) + + check(err) + + defer jpegImage.Close() + + _, err = jpeg.DecodeConfig(jpegImage) + + if err != nil { + return false + } + + return true +} + // Fatal func check(err error) {