Skip to content

Instantly share code, notes, and snippets.

@uzulla
Last active December 17, 2015 09:48
Show Gist options
  • Save uzulla/5589791 to your computer and use it in GitHub Desktop.
Save uzulla/5589791 to your computer and use it in GitHub Desktop.
Glitch jpeg, test perl code.
use CFE::Image::SimpleGlitch;
my $sg = new CFE::Image::SimpleGlitch();
for(1..100){
$sg->load( 'in.jpg' )->do_glitch($ARGV[0])->write( "out$_.jpg" );
}
package CFE::Image::SimpleGlitch;
use Mouse;
use File::Slurp;
has raw => (
is => "rw",
);
sub load {
my ($self, $filename) = @_;
my $_raw = read_file($filename) or die "load file error: $filename";
$self->raw($_raw);
return $self;
}
sub write{
my ($self, $filename) = @_;
write_file($filename, $self->raw) or die "write file error: $filename";
return $self;
}
sub get_random_str{
my ($self, $num) = @_;
my @char_tmp = ('a'..'z','A'..'Z','0'..'9');
my $char_tmp_len = scalar(@char_tmp);
my $str = '';
for(1..$num){
$str .= $char_tmp[ int(rand $char_tmp_len) ];
}
return $str;
}
sub glitch_type_a {
my ($self, $raw, $max_jump_window_param, $random_param) = @_;
my $max_jump_window = length($raw) * $max_jump_window_param;
my $offset = 100;
while(1){
my $total_len = length($raw);
$offset += int(rand $max_jump_window);
$offset = $total_len if($offset > $total_len);
# cut head and tail.
my $head = substr($raw, 0, $offset);
my $tail = substr($raw, $offset, $total_len-$offset);
# generate padding
my $padding = $self->get_random_str( int(rand $random_param) );
# connect
$raw = $head . $padding . $tail;
last if($total_len <= $offset);
}
return $raw;
}
sub do_glitch {
my ($self, $type) = @_;
$type ||= int(rand 5)+1;
my $raw = $self->raw;
if($type==1){
$raw =~ s/a/b/g; #thanks shimpei!
}elsif($type==2){
$raw = $self->glitch_type_a($raw, 3 / 4, 10000);
}elsif($type==3){
$raw = $self->glitch_type_a($raw, 3 / 4, 100);
}elsif($type==4){
$raw = $self->glitch_type_a($raw, 1 / 10, 5);
}elsif($type==5){
$raw = $self->glitch_type_a($raw, 1 / 2, 50000);
}elsif($type==6){
$raw = $self->glitch_type_a($raw, 1 / 100, 2);
}else{
die "not implement type call. $type" ;
}
$self->raw($raw);
return $self;
}
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment