#!/bin/bash

# This script requires ghostscript with the png16m output device
#
# It attempts to extract all DCT-encoded images to jpeg files, and
# all other images to png files.
#
# Works by redefining the image, colorimage and filter operators
#
# Cannot possibly work for all PostScript files. May work for most.
# In particular works with the output of bmp2eps and xv.
#
# The author may be emailed as mjr19. The email domain is
# cam.ac.uk. General support is not offered.
#
# MJR July 2010
#
# LICENCE:
#
#  This program is free software; you can redistribute it and/or
#  modify it under the terms of the GNU General Public License version 2
#  as published by the Free Software Foundation.
#  
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#  
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the
#  Free Software Foundation, Inc., 51 Franklin Street,
#  Fifth Floor, Boston, MA  02110-1301, USA.
#
# It may also be found at
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html

# Changes:
#
# 0.6 to 0.7 -- ability to output single image to stdout added
#               (useful for converting bitmap eps files to pdf
#                with "psimages foo.eps - | bmp2pdf > foo.pdf")
#               Released Oct 2010

# 12/2019 -- add -dNOSAFER as quick fix for gs 9.50's increasing paranoia

function prologue () {
  cat <<\EOF
%!

true setglobal
/epsimagedict
<<
/imagecount 1
/epsisdct false
EOF

echo '/prefix ('$output')'

cat <<\EOF
>> def
false setglobal

/image {
    epsimagedict /epsisdct get {
       10 dict begin
       /epsprefix epsimagedict /prefix get def
       epsprefix (-) ne {
          /filename epsprefix length 8 add string def
          filename 0 epsprefix putinterval
          filename epsprefix length (-000.jpg) putinterval
          filename epsimagedict /imagecount get (000) cvs
          dup length 3 exch sub epsprefix length add 1 add exch
          putinterval
          filename = flush
       } { /filename (%stdout) def } ifelse
       /jpeg filename (w) file def
       dup type (dicttype) eq 
       {/DataSource get /ds exch def} % Removes image dict from stack
       {/ds exch def pop pop pop pop} ifelse
       ds 2 string readstring pop jpeg exch writestring
       ds 2 string readstring pop dup <ffe0> eq not
% Are we missing a JFIF header?
       {jpeg <ffe0 0010 4a46494600 0101 00 0001 0001 00 00> writestring} if
       jpeg exch writestring
       /buffer 8192 string def
       { ds buffer readstring exch jpeg exch writestring not {exit} if }
       loop
       filename (%stdout) eq {quit} if
       end
       epsimagedict /imagecount epsimagedict /imagecount get 1 add put
       epsimagedict /epsisdct false put
    }
    {
    10 dict begin
% Get parameters
    dup type (dicttype) eq
    {  /isdict true def
       /imagedict exch def
       /width imagedict /Width get  def
       /height imagedict /Height get def
       /imgmat imagedict /ImageMatrix get def
    }
    {  /isdict false def
       4 index /width exch def
       3 index /height exch def
       1 index /imgmat exch def
    } ifelse
% Get colour space and inversion
    /imgmat
    matrix currentmatrix imgmat matrix concatmatrix 3 get
    0 gt {[1 0 0 -1 0 height]} {matrix} ifelse def
    currentcolorspace
% Construct filename
    /epsprefix epsimagedict /prefix get def
    epsprefix (-) ne {
       /filename epsprefix length 8 add string def
       filename 0 epsprefix putinterval
       filename epsprefix length (-000.png) putinterval
       filename epsimagedict /imagecount get (000) cvs
       dup length 3 exch sub epsprefix length add 1 add exch
       putinterval
       filename = flush
    } { /filename (%stdout) def } ifelse
% This section fixes an unfortunate dvips / gs interaction
    /.setpagesize { /statusdict .systemvar begin .setpagesize end } bind def
    /letter {612 792 /.setpagesize exec} def
    /note /letter load def
    /a4 {595 842 /.setpagesize exec} def
    /legal {612 1008 /.setpagesize exec} def
% end dvips / gs fix
    gsave (png16m) selectdevice
    <<
	/OutputFile filename
%	/GrayValues 256
	/PageSize [width height]
	/HWSize [width height]
    >> setpagedevice
    setcolorspace % matches currentcolorspace above
    isdict {
       imagedict /ImageMatrix imgmat put
       imagedict /Interpolate false put
       imagedict
    }
    { exch pop imgmat exch } ifelse
    image showpage
    filename (%stdout) eq {quit} if
    end
    (nullpage) selectdevice grestore
    epsimagedict /imagecount epsimagedict /imagecount get 1 add put
    } ifelse % is DCT
} bind def

EOF

if $dct
then
  cat <<EOF
/filter { dup /DCTDecode eq
          {pop epsimagedict /epsisdct true put
% Was DCTDecode given its optional dictionary as an operand?
           dup type (dicttype) eq {pop} if
          }
          {filter} ifelse
} bind def

EOF
fi

cat <<\EOF
/colorimage { 3 dict begin
              gsave
              dup 1 eq {/DeviceGray setcolorspace} if
              dup 3 eq {/DeviceRGB setcolorspace} if
              dup 4 eq {/DeviceCMYK setcolorspace} if
              /imgdict 10 dict def
              imgdict /Decode [ 3 index {0 1} repeat ] put
              exch
              dup imgdict /MultipleDataSources 3 -1 roll put
              not {pop 1} if
              /nsrc exch def
              imgdict /ImageType 1 put
              imgdict /DataSource
              nsrc 1 eq {2 index} { [ nsrc 3 add copy pop pop pop] } ifelse
              put nsrc {pop} repeat 
              imgdict /ImageMatrix 3 -1 roll put
              imgdict /BitsPerComponent 3 -1 roll put 
              imgdict /Height 3 -1 roll put
              imgdict /Width 3 -1 roll put
              imgdict image
              grestore
              end
} bind def


(nullpage) selectdevice
/setpagedevice {pop} def
EOF

}

function help() {
cat <<EOF
Usage psimages [-nodct] psfile [image root]

Writes bitmap images found in PostScript (including EPS) file to PNG
or, if stored as DCT images, JPEG images. Output files are named
image-000.png etc., unless the second argument alters the root name
of the image. Cf pdfimages for PDF files.

If the argument -nodct is given, then DCT images are also output as PNGs.
This might also improve compatibility with some PS files slightly.

If the image root is given as -, the first image found is written to
stdout and the code then exits.

Version 0.7a                                             MJR 10/2010

EOF
exit
}

dct=:
if [ "x$1" = x-nodct ]
then
  dct=false
  shift
fi

output="$2"
[ "x$output" = x ] && output=image
if [ "x$output" = x- -a -t 1 ]
then
  echo Stdout appears to be a terminal -- refusing to output to stdout.
  exit 1
fi

[ $# = 0 -o "x$1" = x-h -o "x$1" = x-help ] && help

gs -dNOSAFER -sDEVICE=nullpage -q -dNOPAUSE <(prologue) $1 -c quit


