Class: Origami::Graphics::ImageXObject

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

Constant Summary

Constants inherited from Stream

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

#[], #[]=, #data, #data=, #decode!, #each_key, #encode!, #initialize, #method_missing, parse, #post_build, #pre_build, #rawdata, #rawdata=, #real_type, #set_predictor, #to_obfuscated_str, #to_s, #value

Methods included from StandardObject

#do_type_check, #has_field?, included, #pdf_version_required, #pre_build, #set_default_value, #set_default_values

Methods included from Object

#<=>, #copy, #indirect_parent, #initialize, #is_indirect?, parse, #pdf, #pdf_version_required, #post_build, #pre_build, #reference, #set_indirect, #set_pdf, #size, skip_until_next_obj, #solve, #to_o, #to_s, #type, typeof, #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::Stream

Class Method Details

.from_image_file(path, format = nil) ⇒ Object

Raises:

  • (ArgumentError)


506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
# File 'lib/origami/graphics/xobject.rb', line 506

def self.from_image_file(path, format = nil)

  if path.respond_to?(:read)
    fd = path
  else
    fd = File.open(File.expand_path(path), 'r').binmode
    format ||= File.extname(path) 
    format.slice!(0) if format and format[0,1] == '.'
  end
     
  if ''.respond_to? :force_encoding
    data = fd.read.force_encoding('binary') # 1.9
  else
    data = fd.read
  end

  fd.close

  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.rawdata = data

      image

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

    when 'jb2', 'jbig', 'jbig2'
      image.setFilter :JBIG2Decode
      image.rawdata = data

      image
  else
    raise NotImplementedError, "Unknown file format: '#{format}'"
  end
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_ ]


560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
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
699
700
701
702
703
704
705
706
707
708
709
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
# File 'lib/origami/graphics/xobject.rb', line 560

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

  case (encoding && encoding.value)
    when :DCTDecode then [ 'jpg', self.data ]
    when :JBIG2Decode then [ 'jbig2', self.data ]
    when :JPXDecode then [ 'jp2', self.data ]

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

    case cs = self.ColorSpace.value
      when Color::Space::DEVICE_GRAY
        colortype = 0
        components = 1
      when Color::Space::DEVICE_RGB
        colortype = 2
        components = 3
      when ::Array
        cstype = cs[0].is_a?(Reference) ? cs[0].solve : cs[0]
        case cstype.value
          when :Indexed
            colortype = 3
            components = 3
            csbase = cs[1].is_a?(Reference) ? cs[1].solve : cs[1]
            lookup = cs[3].is_a?(Reference) ? cs[3].solve : cs[3]

          when :ICCBased
            iccprofile = cs[1].is_a?(Reference) ? cs[1].solve : cs[1]
            raise InvalidColorError, 
              "Invalid ICC Profile parameter" unless iccprofile.is_a?(Stream)
            
            case iccprofile.N
              when 1
                colortype = 0
                components = 1
              when 3
                colortype = 2
                components = 3
            else
              raise InvalidColorError,
                "Invalid number of components in ICC profile: #{iccprofile.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 = self.data
    
    hdr = [137, 80, 78, 71, 13, 10, 26, 10].pack('C*')
    chunks = []

    chunks <<
    [
      'IHDR',
      [
        w, h,
        bpc, colortype, 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 colortype == 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 csbase
      palette = ""

      case csbase.value
        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 csbase[0].solve.value
            when :ICCBased
              iccprofile = csbase[1].solve
              raise InvalidColorError, 
                "Invalid ICC Profile parameter" unless iccprofile.is_a?(Stream)
              
              case iccprofile.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: #{iccprofile.N}"
              end
          else
            raise InvalidColorError, "Unsupported color space: #{csbase}"
          end
      else
        raise InvalidColorError, "Unsupported color space: #{csbase}"
      end

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

      chunks <<
      [
        'PLTE',
        palette
      ]

      bpr = w
    else

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

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

    require 'zlib'
     
    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
end