#!/usr/bin/python
# -*- coding: utf-8 -*-

# thumbor imaging service
# https://github.com/thumbor/thumbor/wiki

# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com timehome@corp.globo.com

import subprocess

from thumbor.optimizers import BaseOptimizer


class Optimizer(BaseOptimizer):

    def should_run(self, image_extension, buffer):
        return 'jpg' in image_extension or 'jpeg' in image_extension

    def optimize(self, buffer, input_file, output_file):
        command = [
            self.context.config.JPEGTRAN_PATH,
            '-copy',
            'comments',
            '-optimize',
        ]

        if self.context.config.PROGRESSIVE_JPEG:
            command += [
                '-progressive'
            ]

        command += [
            '-outfile',
            output_file,
            input_file
        ]

        subprocess.call(command)

@@ -244,22 +244,20 @@
 bo.com%0A%0A
-import
+from
  subproc
@@ -259,16 +259,35 @@
 bprocess
+ import Popen, PIPE
 %0A%0Afrom t
@@ -325,16 +325,49 @@
 timizer%0A
+from thumbor.utils import logger%0A
 %0A%0Aclass 
@@ -463,17 +463,8 @@
 urn 
-'jpg' in 
 imag
@@ -479,36 +479,28 @@
 ion 
-or '
+in %5B'.
 jp
-e
 g'
- in image_extension
+, '.jpeg'%5D
 %0A%0A  
@@ -505,24 +505,28 @@
     def 
+run_
 optimize
 (self, b
@@ -521,48 +521,125 @@
 mize
+r
 (self, 
-buffer, input_file, output_file):
+image_extension, buffer):%0A        if not self.should_run(image_extension, buffer):%0A            return buffer%0A
 %0A   
@@ -915,133 +915,383 @@
     
-command += %5B%0A            '-outfile',%0A            output_file,%0A            input_file%0A        %5D%0A%0A        subprocess.call(command)
+jpg_process = Popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE)%0A        output_stdout, output_stderr = jpg_process.communicate(buffer)%0A%0A        if jpg_process.returncode != 0:%0A            logger.warn('jpegtran finished with non-zero return code (%25d): %25s'%0A                        %25 jpg_process.returncode, output_stderr)%0A            return buffer%0A%0A        return output_stdout
 %0A

Use pipes for jpegtran optimizer to avoid temp files creation