Menu
  • HOME
  • TAGS

Internal server error when trying to write an image & an thumbnail using ImageMagick in Perl

Tag: image,perl,imagemagick,image-uploading,perlmagick

This Perl script uploads an image to server and then saves: - a gallery image that fits in 900x900 px - a square gallery thumbnail 140x140 px - adds a line in a js file with the image and thumbnail names

The problem is, that the script sometimes works, sometimes - not. It works fine in one or two of every ten attempts. When it doesn't work, it usually returns "Internal Server Error" and doesn't create two files, nor adds a line in js. But in some cases it creates the both jpg files and doesn't add a line in js (again returning "Internal Server Error"). Very strange behavior - I've tried various changes with no result. What I do wrong?

#!/usr/bin/perl -w
##
##

use strict;
use CGI;
use CGI::Carp qw ( fatalsToBrowser );
use File::Basename;
use Image::Magick;

$CGI::POST_MAX = 1024 * 70000;
my $safe_filename_characters = "a-zA-Z0-9_.-";
my $pic_upload_dir="../data/photos/gallery";
my $lst_upload_dir="../data";
my $lst_file=$lst_upload_dir."/gallery.js";

my $query=new CGI;

my $PictureIndex=$query->param("Snd_AddPhoto_Idx");
my $photoname=$query->param("AddPhoto");

    #upload photo
    if ( !$photoname ) {  
        print "Content-Type: text/plain\n\n";
        print "\n\nThere was a problem uploading your photo (try a smaller size).\n";
        exit;
    }  

    my ( $phname, $phpath, $phextension ) = fileparse ($photoname, qr/\.[^.]*/);
    $photoname = $phname . $phextension;
    $photoname =~ tr/ /_/;
    $photoname =~ s/[^$safe_filename_characters]//g;

    if ( $photoname =~ /^([$safe_filename_characters]+)$/ ) {  
        $photoname = $1;
    }  
    else {  
        die "Filename contains invalid characters";
    }  

        # force correct filename for temporary file
        $photoname="tempphoto_zmm_gallery_".$PictureIndex.$phextension;

    my $upload_photohandle = $query->upload("AddPhoto");

    open ( UPLOADPHOTO, ">$pic_upload_dir/$photoname" ) or die "$!";
    binmode UPLOADPHOTO;
    while ( <$upload_photohandle> ) {  
        print UPLOADPHOTO;
    }  
    close UPLOADPHOTO;

    # resize photo
    my($photoimage) = Image::Magick->new;
    open(PHOTOIMAGE, "$pic_upload_dir/$photoname") or die "Unable to open temporary image file!\n";
    $photoimage->Read(file=>\*PHOTOIMAGE);
    close(PHOTOIMAGE);

    $photoimage->Resize(geometry=>'900x900', blur=>0.8);
    $photoimage->Set(Quality=>'75%');

    # write ready photo as jpg
    my $readyphotoname="pic".$PictureIndex.".jpg";
    open(READYIMAGE, ">$pic_upload_dir/$readyphotoname") or die "Unable to write ready image file!\n";
    $photoimage->Write(file=>\*READYIMAGE, filename=>$readyphotoname);
    close(READYIMAGE);
    system("chmod 777 $pic_upload_dir/$readyphotoname");

    # resize thumbnail
    my($thumbimage) = Image::Magick->new;
    open(THUMBIMAGE, "$pic_upload_dir/$photoname") or die "Unable to open temporary image file!\n";
    $thumbimage->Read(file=>\*THUMBIMAGE);
    close(THUMBIMAGE);

    $thumbimage->Resize(geometry=>'140x140^', blur=>0.8);
    $thumbimage->Set(gravity=>'Center');
    $thumbimage->Crop(geometry=>'140x140+0+0');
    $thumbimage->Set(Quality=>'30%');

    # write ready thumbnail as jpg
    my $readythumbname="tbn".$PictureIndex.".jpg";
    open(READYTHUMB, ">$pic_upload_dir/$readythumbname") or die "Unable to write ready image file!\n";
    $thumbimage->Write(file=>\*READYTHUMB, filename=>$readythumbname);
    close(READYTHUMB);
    system("chmod 777 $pic_upload_dir/$readythumbname");

    # delete temporary file
    my($temporary_file)=$pic_upload_dir."/".$photoname;
    unlink($temporary_file) == 0;


# add pic in js gallery list

    # prepare new pic record
    my $NewGalRecord="GalleryList.push(new Array(\"pic".$PictureIndex.".jpg\",\"tbn".$PictureIndex.".jpg\",\"\",\"\"));\n";

    # add to file
    open(JS,">>$lst_file") || die "Failed to open $lst_file\n";
    printf JS $NewGalRecord;
    close JS;
    system("chmod 777 $lst_file");

# print confirmation

...
...
...


exit;

Best How To :

I think I've solved the problem. Obviously there's no need to read the temp file twice. After saving the 'big' image, we can continue manipulate it and then save again as thumbnail. Double reading of the temp file apparently causes conflict. Something like 'Sharing violation' - just a shot in the dark. But now the script works fine. Separately, far removed the rows Set(Quality=>). I don't know whether they have anything to do with the problem, but this will be subject to future testing. Here are the changes:

    # resize photo
    my($photoimage) = Image::Magick->new;
    open(PHOTOIMAGE, "$pic_upload_dir/$photoname") or die "Unable to open temporary image file!\n";
    $photoimage->Read(file=>\*PHOTOIMAGE);
    close(PHOTOIMAGE);

    $photoimage->Resize(geometry=>'900x900', blur=>0.8);

    # write ready photo as jpg
    my $readyphotoname="pic".$PictureIndex.".jpg";
    open(READYIMAGE, ">$pic_upload_dir/$readyphotoname") or die "Unable to write ready image file!\n";
    $photoimage->Write(file=>\*READYIMAGE, filename=>$readyphotoname);
    close(READYIMAGE);
    system("chmod 777 $pic_upload_dir/$readyphotoname");

    # resize thumbnail
    $photoimage->Resize(geometry=>'140x140^', blur=>0.8);
    $photoimage->Set(gravity=>'Center');
    $photoimage->Crop(geometry=>'140x140+0+0');

    # write ready thumbnail as jpg
    my $readythumbname="tbn".$PictureIndex.".jpg";
    open(READYTHUMB, ">$pic_upload_dir/$readythumbname") or die "Unable to write ready image file!\n";
    $photoimage->Write(file=>\*READYTHUMB, filename=>$readythumbname);
    close(READYTHUMB);
    system("chmod 777 $pic_upload_dir/$readythumbname");

    # delete temporary file
    my($temporary_file)=$pic_upload_dir."/".$photoname;
    unlink($temporary_file) == 0;

Uploading PNG to Website Server

php,mysql,image,png

You're not declaring $image_width or $image-height and you are referencing $image instead of $source_image in imagecopyresampled(). I too was getting a plain white image, but after this I get the expected result: $image = $_FILES['file']['tmp_name']; $image_name = $_FILES['file']['name']; $ext = pathinfo($image_name, PATHINFO_EXTENSION); $location = "Profiles/{$user}/Picture/{$image_name}"; $new_image = imagecreatetruecolor(100, 100); $source_image...

Version-dependent fallback code

perl

Many recent features are not forward-compatible. As you've seen, you'll get compile-time errors using a feature that is too new for the version of perl you are running. Using block-eval won't help, because the contents of the block need to be valid for the current perl interpreter. You are on...

What does this horribly ugly (yet somehow secretly beautiful) Perl code do?

perl,formatting,deobfuscation

Passing the code to Google returns this page that explains qrpff is a Perl script created by Keith Winstein and Marc Horowitz of the MIT SIPB. It performs DeCSS in six or seven lines. The name itself is an encoding of "decss" in rot-13. See also qrpff explained....

Can't get images from storage laravel 5

php,image,laravel

What you are trying to do is not possible in the storage directory but possible only in public directory, also exposing the path or URL to your laravel storage directory creates some vulnerability and its bad practice However there is a way to workaround it: First, you need an Image...

Images not loaded from master page in directory

asp.net,image

@Brendan Hannemann show me a link that where is expaint. The code i must use is: <img src="<%=ResolveUrl("~/afbeeldingen/berichten.png") %>" alt="nieuwe berichten" id="berichten" /> ...

Upload image to server from gallary or camera android

android,image,image-uploading

Here is the Code piece for Taking a Picture through Default Camera (here I implemented Intent to to fetch the image). After that store it to SD card(here a new file will be created and the newly taken image will be stored ); and if you don't want to store...

Check for decimal point and add it at the end if its not there using awk/perl

regex,perl,shell,awk

In awk Just sub for those fields awk -F, -vOFS="," '{sub(/^[^\.]+$/,"&.",$6);sub(/^[^\.]+$/,"&.",$11)}1' file or sed sed 's/^\(\([^,]*,\)\{5\}[^.,]\+\),/\1./;s/^\(\([^,]*,\)\{10\}[^.,]\+\),/\1./' file ...

How to crop image from center using wp_image_editor

wordpress,image,wordpress-plugin,resize-crop,wp-image-editor

Try this code: $crop = array( 'center', 'center' ); resize( $max_w, $max_h, $crop); ...

-M Script start time minus file modification time, in days

perl,perldoc

I think this explains what you are seeing perl -E 'say "START TIME",$^T; qx(touch $_), sleep(5), say -M for "/tmp/file"; say "STAT ON FILE", (stat(_))[9]' output when I ran it START TIME1434460114 0 STAT ON FILE1434460114 1) script starts $^T is set to 1434460114 2) almost immediately the file "/tmp/file"...

Capture tee's argument inside piped Perl execution

perl,unix

The short answer is - you can't. tee is a separate process with it's own arguments. There is no way to access these arguments from that process. (well, I suppose you could run ps or something). The point of tee is to take STDOUT write some of it to a...

Crop does not work for gallery images

android,image,crop

Try this Working code Buttonclick to take camera dialog.show(); Add this inside Oncreate() captureImageInitialization(); try this it will work // for camera private void captureImageInitialization() { try { /** * a selector dialog to display two image source options, from * camera ‘Take from camera’ and from existing files ‘Select...

Preload image for seamless background image change in JavaScript

javascript,image,preload

You're not actually passing a callback function: NewImage.onload = ImageLoadComplete(); You're passing in the result of calling ImageLoadComplete(), which means you call your callback immediately. Don't call the function and your code should work as expected (most of the time): NewImage.onload = ImageLoadComplete; One issue that you'll encounter is that...

Why this exclusion not working for long sentences?

text-processing,perl

You're using the wrong syntax: [] is used to match a character class, while here you're trying to match a number of occurences of ., which can be done using {}: perl -ne 'print unless /.{240,}/' input.txt > output.txt Also, as suggested by salva in the comments, the pattern can...

How to convert an Image to Mat Android

android,image,bitmap,mat

I think that i found a possible answer. I give to my ImageReader a simple plane format like JPEG. reader = ImageReader.newInstance(previewSize.getWidth(),previewSize.getHeight(), ImageFormat.JPEG, 2); Then i do that : ByteBuffer bb = image.getPlanes()[0].getBuffer(); byte[] buf = new byte[bb.remaining()]; imageGrab = new Mat(); imageGrab.put(0,0,buf); ...

Loading images into html5 canvas

javascript,node.js,image,html5-canvas,sails.js

Yes, use a CDN if you have the option. Pros: - Save enormously on website load time / speed. - Better for organization / maintenance. Cons: - One more paid account; but you may end up having to upgrade your hosting anyway if your images continue to add up with...

unable to understand qr interpolation

regex,perl

The chapter of the Perl documentation that deals with this is called perlre. In the extended pattern matching section it explains this. Starting in Perl 5.14, a "^" (caret or circumflex accent) immediately after the "?" is a shorthand equivalent to d-imsx . Flags (except "d" ) may follow the...

How to prevent exceeding matrix dimensions while dividing an image into blocks?

image,matlab,image-processing,image-segmentation

If you simply want to ignore the columns/rows that lie outside full sub-blocks, you just subtract the width/height of the sub-block from the corresponding loop ranges: overlap = 4 blockWidth = 8; blockHeight = 8; count = 1; for i = 1:overlap:size(img,1) - blockHeight + 1 for j = 1:overlap:size(img,2)...

Change Background image in WPF using C# [duplicate]

c#,wpf,image,background,resources

Firstly, add a Folder to your Solution (Right click -> Add -> Folder), name it something like "Resources" or something useful. Then, simply add your desired image to the folder (Right click on folder -> Add -> Existing item). Once it's been added, if you click on the image and...

Perl Debugging Using Flags

perl,debugging,script-debugging

In perl, compile time is also run time. So there's really not a great deal of advantage in using #define type statements. My usual trick is: my $debug = 0; $debug += scalar grep ( "-d", @ARGV ); (GetOpt is probably honestly a better plan though) And then use: print...

How to pass a hash as optional argument to -M in command line

perl,hash,package,command-line-interface

Looking at perlrun use: perl -Mfeature=say "-Mconstant {c1 => 'foo', c2 => 'bar'}" -e"say c1,c2" ...

Looping variables

perl,scripting

As per my comment, most of the functionality of your program is provided by the Math::Vector::Real module that you're already using It looks like you want the angle in degrees between successive pairs of 3D vectors in your file. This code creates vectors from each line in the file until...

Saving images with more than 8 bits per pixel in matlab

image,matlab,image-processing,computer-vision

You can use the bitdepth parameter to set that. imwrite(img,'myimg.png','bitdepth',16) Of course, not all image formats support all bitdepths, so make sure you are choosing the the right format for your data....

Find numbers in a file and change their value with perl

regex,perl

You can just match the numbers that are less than one.. and replace with 1: perl -pe 's/\b0\.\d+/1/g' file See DEMO...

How to match and remove the content preceding it from a file in unix [closed]

mysql,perl,sed,solaris

with GNU sed sed -n '1,/-- Final view structure for view `view_oss_user`/p' this will print lines from 1 till pattern found, others will not be printed or if you want to exclude pattern line then sed -n '1,/-- Final view structure for view `view_oss_user`/p' | sed '$d' ...

Fetch a saved image and display

ios,image,path

if you know the image path or name then you may implement something like this. - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{ UICollectionViewCell *cell = [[UICollectionViewCell alloc]initWithFrame:CGRectMake(0, 0, 50.0, 50.0)]; cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath]; UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 50.0, 50.0)]; [imageView setImage:[UIImage...

How to search images by name inside a folder?

php,mysql,image

This looks like a job for glob, which returns an array of file names matching a specified pattern. I'm aware of the other answer just posted, but let's provide an alternative to regex. According to the top comment on the docs page, what you could do is something like this:...

Why Filter::Indent::HereDoc complain when blank line in middle of HereDoc

perl,heredoc

The documentation says: If there is no terminator string (so the here document stops at the first blank line), then enough whitespace will be stripped out so that the leftmost character of the document will be flush with the left margin, e.g. print <<; Hello, World! # This will print:...

what is the nodejs package for s3 image upload

node.js,image,amazon-s3

I recommend using s3-uploader, it's flexible and efficient resize, rename, and upload images to Amazon S3.

adding link_to with image_tag and image path both

html,ruby-on-rails,image,ruby-on-rails-4,svg

Remove the space after image_tag. <%= link_to '#' do %> My Project <%= image_tag('logo.svg', "data-svg-fallback" => image_path('logo.svg'), :align=> "left" ,:style => "padding-right: 5px;") %> <% end %> ...

Verify data integrity for varbinary column

sql,sql-server,image,sql-server-2012

This worked for me: How to export image field to file? The short version without the cursor looks like this: DECLARE @ImageData VARBINARY(max) DECLARE @FullPathToOutputFile NVARCHAR(2048); SELECT @ImageData = pic FROM Employees WHERE id=5 SET @FullPathToOutputFile = 'C:\51.jpg' DECLARE @ObjectToken INT EXEC sp_OACreate 'ADODB.Stream', @ObjectToken OUTPUT; EXEC sp_OASetProperty @ObjectToken, 'Type',...

Import java package from Matlab deploytool to Android Studio App

java,android,image,matlab,jar

Java components that are generated from MATLAB code using deploytool (or using other functionality from MATLAB deployment products such as MATLAB Compiler, MATLAB Builder etc.) depend on the MATLAB Compiler Runtime (MCR). The MCR has much too large a footprint to run on an Android device, and it's really not...

Trouble generating Barcode using ZXing library with large data

java,android,image,barcode,zxing

You can upload the barcode image you produced to the ZXing Decoder Online to confirm if it is valid: http://zxing.org/w/decode.jspx There is no intrinsic limit to the length of a Code 128 barcode, and all the characters you have are valid. Having said that, with Code 128A barcodes, having more...

Is there a way to make images take up less space in an apk or will I have to use an APK expansion file? [closed]

android,image,android-studio,apk-expansion-files

First of all, mipmap folders are for your app icon only. Any other other resources must be placed in drawable folder. Take a look at this post mipmap vs drawable. And to answer your question, there are several ways to optimize your images and layout to decrease the size of...

Create mask from bwtraceboundary in Matlab

image,matlab,image-processing,mask,boundary

It's very simple. I actually wouldn't use the code above and use the image processing toolbox instead. There's a built-in function to remove any white pixels that touch the border of the image. Use the imclearborder function. The function will return a new binary image where any pixels that were...

Regex in Perl Uninitialized $1

regex,perl

$1 is the value captured by the first capture (()), but you have no captures in your pattern. Fix: /(?<=File `..\/)(.*)(?=')/ Simplified: m{File `../(.*)'} More robust: m{File `../([^']*)'} ...

I can't download images uploaded ​​with “move_uploaded_file()” code on filezilla

php,html,image,move

Suppose you rename one of the files which does not works for download to test.jpg to test.gif (assuming that jpg are not working). If it does not work.. Check the permission for read and writes in your control panel for ftp user...

Perl : Display perl variable awk sed echo

perl

You can do that using a Perl regex pattern my $calculate; ($calculate = $1) =~ tr~,~/~ if $value =~ /SP=[^:]*:([^;]*)/; ...

How to resize image according from screen resolution on html css

html,css,image,screen-resolution

HTML : <div class="img-div"> <img src="path-to-image"> </div> CSS : .img-div { height:100%; width:100%;} img { max-width:100% } ...

calling cgi script from other cgi script

perl,cgi

A CGI program normally expects to fetch the parameter values from the environment variable QUERY_STRING. Passing parameter values on the command line is a debugging facility, and works only when the program is run from the command prompt You could try something like this my $result = do { local...

Opening multiple files in perl array

arrays,perl

You just need to enclose the code that handles a single file in a loop that iterates over all of the log files You should also reconsider the amount of comments that you use. It is far better to write your code and choose identifiers so that the behaviour is...

Create a border around image when active/clicked

css,image,border,active

This option is suitable? input{ display: none; } label{ display: inline-block; width: 100px; height: 100px; position: relative; border: 4px solid transparent; } input:checked + label{ border: 4px solid #f00; } <input type="radio" id="r1" name="radio" /> <label for="r1"> <img src="http://www.auto.az/forum/uploads/profile/photo-thumb-1.jpg?_r=1431896518" alt="" /> </label> <input type="radio" id="r2" name="radio" /> <label for="r2"> <img...

How to make a Javafx Image Crop App

java,image,canvas,graphics,javafx

Your question is too much to be answered on StackOverflow. I suggest you start with reading the official Oracle documentation about JavaFX. However, since it's an interesting topic, here's the answer in code. There are several things you need to consider: use an ImageView as container use a ScrollPane in...

PHP How to not cache generated HTML but cache static data like images/js/css

javascript,php,css,image,caching

you can use a htaccess to define files that you want to be cached all you want is to make a .htaccess file in the main directory of your website and add this code example: # cache images/pdf docs for 1 week <FilesMatch "\.(ico|pdf|jpg|jpeg|png|gif)$"> Header set Cache-Control "max-age=604800, public, must-revalidate"...

Python Resize Multiple images ask user to continue

python,xml,image,resize

Change your final loop to: for idx, image in enumerate(imgPath): #img resizing goes here count_remaining = len(imgPath) - (idx+1) if count_remaining > 0: print("There are {} images left to resize.".format(count_remaining)) response = input("Resize image #{}? (Y/N)".format(idx+2)) #use `raw_input` in place of `input` for Python 2.7 and below if response.lower() !=...

Perl: Using Text::CSV to print AoH

arrays,perl,csv

Pretty fundamentally - CSV is an array based data structure - it's a vaguely enhanced version of join. But the thing you need for this job is print_hr from Text::CSV. First you need to set your header order: $csv->column_names (@names); # Set column names for getline_hr () Then you can...

Command line arguments in Perl

perl

$! and $_ are global variables. For more information you can read here $_ The default input and pattern-searching space $! If used in a numeric context, yields the current value of the errno variable, identifying the last system call error. If used in a string context, yields the corresponding...

Create unicode character with pack

perl,unicode

Why do I get ff and not c3bf when using pack ? This is because pack creates a character string, not a byte string. > perl -MDevel::Peek -e 'Dump(pack("U", 0xff));' SV = PV(0x13a6d18) at 0x13d2ce8 REFCNT = 1 FLAGS = (PADTMP,POK,READONLY,pPOK,UTF8) PV = 0xa6d298 "\303\277"\0 [UTF8 "\x{ff}"] CUR =...

Dynamically resize side-by-side images with different dimensions to the same height

javascript,html,css,image

If it's responsive, use percentage heights and widths: html { height: 100%; width: 100%; } body { height: 100%; width: 100%; margin: 0; padding: 0; } div.container { width: 100%; height: 100%; white-space: nowrap; } div.container img { max-height: 100%; } <div class="container"> <img src="http://i.imgur.com/g0XwGQp.jpg" /> <img src="http://i.imgur.com/sFNj4bs.jpg" /> </div>...

Counting occurrences of a word in a string in Perl

regex,perl

I get the correct number - 6 - for the first string However your method is wrong, because if you count the number of pieces you get by splitting on the regex pattern it will give you different values depending on whether the word appears at the beginning of the...

Excel VBA 2013 Print Image

image,excel-vba,printing

One option is to call Windows Print dialog via shell command. Example: (Full code) Option Explicit Private Declare Function apiShellExecute Lib "shell32.dll" Alias "ShellExecuteA" ( _ ByVal hwnd As Long, _ ByVal lpOperation As String, _ ByVal lpFile As String, _ ByVal lpParameters As String, _ ByVal lpDirectory As String,...