| Class | Origami::Filter::LZW |
| In: |
sources/parser/filters.rb
|
| Parent: | Object |
Decodes given data using LZW compression method.
| stream: | The data to decode. |
# File sources/parser/filters.rb, line 496
496: def decode(string)
497:
498: result = ""
499: bstring = string2binary(string)
500: codesize = 9
501: table = clear({})
502: prevbyte = nil
503:
504: until bstring.empty? do
505:
506: byte = binary2byte(bstring, codesize)
507:
508: case table.size
509: when 510 then codesize = 10
510: when 1022 then codesize = 11
511: when 2046 then codesize = 12
512: when 4094
513: if byte != CLEARTABLE
514: then
515: raise InvalidLZWData, "LZW table is full and no clear flag was set"
516: end
517: end
518:
519: if byte == CLEARTABLE
520: codesize = 9
521: code = EOD
522: clear table
523: prevbyte = nil
524: redo
525: elsif byte == EOD
526: break
527: else
528: if prevbyte.nil?
529: prevbyte = byte
530: result << table.index(byte)
531: redo
532: else
533: if table.has_value?(byte)
534: entry = table.index(byte)
535: else
536: entry = table.index(prevbyte)
537: entry += entry[0,1]
538: end
539:
540: result << entry
541: table[table.index(prevbyte) + entry[0,1]] = table.size
542: prevbyte = byte
543: end
544: end
545: end
546:
547: if not @params[:Predictor].nil?
548: colors = @params.has_key?(:Colors) ? @params[:Colors].to_i : 1
549: bpc = @params.has_key?(:BitsPerComponent) ? @params[:BitsPerComponent].to_i : 8
550: columns = @params.has_key?(:Columns) ? @params[:Columns].to_i : 1
551:
552: result = Predictor.do_post_prediction(result, @params[:Predictor].to_i, colors, bpc, columns)
553: end
554:
555: result
556: end
Encodes given data using LZW compression method.
| stream: | The data to encode. |
# File sources/parser/filters.rb, line 447
447: def encode(string)
448:
449: if not @params[:Predictor].nil?
450: colors = @params.has_key?(:Colors) ? @params[:Colors].to_i : 1
451: bpc = @params.has_key?(:BitsPerComponent) ? @params[:BitsPerComponent].to_i : 8
452: columns = @params.has_key?(:Columns) ? @params[:Columns].to_i : 1
453:
454: string = Predictor.do_pre_prediction(string, @params[:Predictor].to_i, colors, bpc, columns)
455: end
456:
457: codesize = 9
458: result = byte2binary(CLEARTABLE)
459: table = clear({})
460:
461: s = ''
462: string.each_byte do |byte|
463: char = byte.chr
464:
465: case table.size
466: when 512 then codesize = 10
467: when 1024 then codesize = 11
468: when 2048 then codesize = 12
469: when 4096
470: codesize = 9
471: result << byte2binary(CLEARTABLE,codesize)
472: clear table
473: redo
474: end
475:
476: it = s + char
477: if table.has_key?(it)
478: s = it
479: else
480: result << byte2binary(table[s], codesize)
481: table[it] = table.size
482: s = char
483: end
484: end
485:
486: result << byte2binary(table[s], codesize)
487: result << byte2binary(EOD,codesize)
488:
489: binary2string(result)
490: end