Class: Origami::Graphics::ImageXObject

Inherits:
Stream
  • Object
show all
Includes:
XObject
Defined in:
lib/origami/page.rb,
lib/origami/graphics/xobject.rb

Constant Summary

Constants inherited from Stream

Stream::DEFINED_FILTERS, Stream::TOKENS

Constants included from StandardObject

StandardObject::DEFAULT_ATTRIBUTES

Constants included from Object

Object::TOKENS

Instance Attribute Summary

Attributes inherited from Stream

#dictionary

Attributes included from Object

#file_offset, #generation, #no, #objstm_offset, #parent

Class Method Summary collapse

Instance Method Summary collapse

Methods included from XObject

included

Methods inherited from Stream

#[], #[]=, #cast_to, #data, #data=, #decode!, #each_filter, #each_key, #each_pair, #encode!, #encoded_data, #encoded_data=, #filters, #initialize, #key?, #keys, parse, #post_build, #pre_build, #set_predictor, #to_obfuscated_str, #to_s, #value

Methods included from TypeGuessing

#guess_type

Methods included from FieldAccessor

#method_missing, #respond_to_missing?

Methods included from StandardObject

included, #pre_build, #version_required

Methods included from Object

#cast_to, #copy, #document, #export, included, #indirect?, #indirect_parent, #initialize, #logicalize, #logicalize!, #native_type, #numbered?, parse, #post_build, #pre_build, #reference, #set_document, #set_indirect, skip_until_next_obj, #solve, #to_o, #to_s, #type, typeof, #version_required, #xrefs

Constructor Details

This class inherits a constructor from Origami::Stream

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class Origami::FieldAccessor

Class Method Details

.from_image_file(path, format = nil) ⇒ Object

Raises:

  • (ArgumentError)


670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
# File 'lib/origami/graphics/xobject.rb', line 670

def self.from_image_file(path, format = nil)
  if path.respond_to?(:read)
    data = path.read
  else
    data = File.binread(File.expand_path(path))
    format ||= File.extname(path)[1..]
  end

  image = ImageXObject.new

  raise ArgumentError, "Missing file format" if format.nil?
  case format.downcase
  when 'jpg', 'jpeg', 'jpe', 'jif', 'jfif', 'jfi'
    image.setFilter :DCTDecode
    image.encoded_data = data

  when 'jp2', 'jpx', 'j2k', 'jpf', 'jpm', 'mj2'
    image.setFilter :JPXDecode
    image.encoded_data = data

  when '.b2', 'jbig', 'jbig2'
    image.setFilter :JBIG2Decode
    image.encoded_data = data
  else
    raise NotImplementedError, "Unknown file format: '#{format}'"
  end

  image
end

Instance Method Details

#to_image_fileObject

Converts an ImageXObject stream into an image file data. Output format depends on the stream encoding:

* JPEG for DCTDecode
* JPEG2000 for JPXDecode
* JBIG2 for JBIG2Decode
* PNG for everything else

Returns an array of the form [ _format_, _data_ ]

Raises:



710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
# File 'lib/origami/graphics/xobject.rb', line 710

def to_image_file
  encoding = self.Filter
  encoding = encoding[0] if encoding.is_a? ::Array

  case encoding&.value
  when :DCTDecode then return ['jpg', data]
  when :JBIG2Decode then return ['jbig2', data]
  when :JPXDecode then return ['jp2', data]
  end

  # Assume PNG data.

  raise InvalidColorError, "No colorspace specified" unless self.ColorSpace

  case cs = self.ColorSpace.value
  when Color::Space::DEVICE_GRAY
    color_type = 0
    components = 1
  when Color::Space::DEVICE_RGB
    color_type = 2
    components = 3
  when ::Array
    cs_type = cs[0]
    case cs_type
    when :Indexed
      color_type = 3
      components = 3
      cs_base = cs[1]
      lookup = cs[3]

    when :ICCBased
      icc_profile = cs[1]
      unless icc_profile.is_a?(Stream)
        raise InvalidColorError,
          "Invalid ICC Profile parameter"
      end

      case icc_profile.N
      when 1
        color_type = 0
        components = 1
      when 3
        color_type = 2
        components = 3
      else
        raise InvalidColorError,
          "Invalid number of components in ICC profile: #{icc_profile.N}"
      end
    else
      raise InvalidColorError, "Unsupported color space: #{self.ColorSpace}"
    end
  else
    raise InvalidColorError, "Unsupported color space: #{self.ColorSpace}"
  end

  bpc = self.BitsPerComponent || 8
  w, h = self.Width, self.Height
  pixels = data

  hdr = [137, 80, 78, 71, 13, 10, 26, 10].pack('C*')
  chunks = []

  chunks <<
    [
      'IHDR',
      [
        w, h,
        bpc, color_type, 0, 0, 0
      ].pack("N2C5")
    ]

  if self.Intents
    intents =
      case self.Intents.value
      when Intents::PERCEPTUAL then 0
      when Intents::RELATIVE then 1
      when Intents::SATURATION then 2
      when Intents::ABSOLUTE then 3
      else
        3
      end

    chunks <<
      [
        'sRGB',
        [intents].pack('C')
      ]

    chunks << ['gAMA', [45455].pack("N")]
    chunks <<
      [
        'cHRM',
        [
          31270,
          32900,
          64000,
          33000,
          30000,
          60000,
          15000,
          6000
        ].pack("N8")
      ]
  end

  if color_type == 3
    lookup =
      case lookup
      when Stream then lookup.data
      when String then lookup.value
      else
        raise InvalidColorError, "Invalid indexed palette table"
      end

    raise InvalidColorError, "Invalid base color space" unless cs_base
    palette = ""

    case cs_base
    when Color::Space::DEVICE_GRAY
      lookup.each_byte do |g|
        palette << Color.gray_to_rgb(g).pack("C3")
      end
    when Color::Space::DEVICE_RGB
      palette << lookup[0, (lookup.size / 3) * 3]

    when Color::Space::DEVICE_CMYK
      (lookup.size / 4).times do |i|
        cmyk = lookup[i * 4, 4].unpack("C4").map! { |c| c.to_f / 255 }
        palette << Color.cmyk_to_rgb(*cmyk).map! { |c| (c * 255).to_i }.pack("C3")
      end
    when ::Array

      case cs_base[0]
      when :ICCBased
        icc_profile = cs_base[1]
        unless icc_profile.is_a?(Stream)
          raise InvalidColorError,
            "Invalid ICC Profile parameter"
        end

        case icc_profile.N
        when 1
          lookup.each_byte do |g|
            palette << Color.gray_to_rgb(g).pack("C3")
          end
        when 3
          palette << lookup[0, (lookup.size / 3) * 3]
        else
          raise InvalidColorError,
            "Invalid number of components in ICC profile: #{icc_profile.N}"
        end
      else
        raise InvalidColorError, "Unsupported color space: #{cs_base}"
      end
    else
      raise InvalidColorError, "Unsupported color space: #{cs_base}"
    end

    if icc_profile
      chunks <<
        [
          'iCCP',
          'ICC Profile' + "\x00\x00" + Zlib::Deflate.deflate(icc_profile.data, Zlib::BEST_COMPRESSION)
        ]
    end

    chunks <<
      [
        'PLTE',
        palette
      ]

    bpr = w

  else # color_type != 3
    if icc_profile
      chunks <<
        [
          'iCCP',
          'ICC Profile' + "\x00\x00" + Zlib::Deflate.deflate(icc_profile.data, Zlib::BEST_COMPRESSION)
        ]
    end

    bpr = (bpc >> 3) * components * w
  end

  nrows = pixels.size / bpr
  nrows.times do |irow|
    pixels.insert(irow * bpr + irow, "\x00")
  end

  chunks <<
    [
      'IDAT',
      Zlib::Deflate.deflate(pixels, Zlib::BEST_COMPRESSION)
    ]

  if self.Metadata.is_a?(Stream)
    chunks <<
      [
        'tEXt',
        "XML:com.adobe.xmp" + "\x00" + self.Metadata.data
      ]
  end

  chunks << ['IEND', '']

  ['png',
    hdr + chunks.map! { |chk|
      [chk[1].size, chk[0], chk[1], Zlib.crc32(chk[0] + chk[1])].pack("NA4A*N")
    }.join]
end