Image resizing and cropping

Hi,
I want to convert images to thumbnails with a 'standard' format - I need all images to have the same width and height.
So I need to resize and then crop the images. Is this possibe with JAI? Are there other libraries which can do this better?
I've read about ImageMagick - are the Java interfaces to ImageMagick good?
/regards, Håkan Jacobsson

Depending on the format of your files, you need not go into JAI. You may be able to do what you want with ImageIO.
You just need to load the image, select the part you want, then check the length to width ratio to make sure it is appropriate, if not, then adjust it as such.
If you want to get a 100, 100 thumb from a 1024, 768 image you can do this:
BufferedImage bi = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bi.createGraphics();
g.drawImage(my1024x768, 0, 12, 100, 75, Color.BLACK, null);
g.dispose();please note, that to get 1024 shunk up to 100, you need to divide by 10.24, when you do the same to the height of the image, you get 75, this leaves 25 pixels--so I centered the image at 12.
to save the thumb in JPG:
File f = new File(myFileNameAndPath);
f.createFile();
ImageIO.write(bi, "JPEG", f);**WARNING** untested code.

Similar Messages

  • Lightroom 3 Beta-Image Rotate and Crop Tool

    Good Morning Adobe,
    First of all let me say Lightroom 3 is fantastic! I do have a couple of suggestions that might make the image editing more efficient. I find that I use the image rotate and crop tools frequently and think that possibly locating these 2 features below the image in the tool bar with the loupe view/zoom fit/before and after will allow the user to edit the images more efficiantly.
    I believe that this is an incredible program and can't wait to see the finished product!
    I will offer more suggestions as they evolve.
    Thank you Adobe! You are the BEST!
    D.A.    

    Thank you...I discovered this answer online from another post last night and tried it.  (Since I didn't re-size the thumbnails, I wasn't aware that you could do this.)  After re-starting Lightroom and my computer, the crop issue corrected itself.  Thank you very much for your response.  It worked!

  • Resize and crop images to a specific width and height

    Hi,
    I want to convert images to thumbnails with a 'standard' format - I need all images to have the same width and height.
    So I need to resize and then crop the images. Is this possibe with JAI? Are there other libraries which can do this better?
    I've read about ImageMagick - are the Java interfaces to ImageMagick good?
    /best regards, Håkan Jacobsson - System developer in Sweden

    Duplicate posting, answers are here
    http://forums.sun.com/thread.jspa?threadID=5419291
    Pleas don't duplicate unless you note that you have done so and provide pointers to the duplicates - as I'm sure you're aware. . .

  • PHP -Mysql image resize and upload

    All,
    Any good ideas, code out there to help me do a PHP MySQL image resize, uploade and display? Thanks for your help!

    For upload image, u may look at the similar thread HERE

  • Open a disk image file and crop it to an Image control

    Hi Folks,
    I am trying to allow my users (in a browser) to select/open a disk file (image type) so that they can see it and then save it to the server.  I can use the FileReference object just fine, and load its 'result' directly into a MX:Image control.  However, before I do that I would like to crop the selected imaged to a square shape.  I'd also like to resize the image down, but that will come later, once I get the cropping working.
    I am essentially taking the FileReference result bytearray and converting that to a BitmapData object.  Then, I 'extract' a square of data from that BitmapData object into a new BitmapData object.  Then I need to get *that* BitmapData object into the mx:image control.  I tried using a Bitmap to do so, however the resulting mx:image, while 'sized' correctly, displays as a blank white region.  All along, the variables seem to be 'full' of data and seem to have properly set attributes.  I've looked up quite a few sites that demonstrate cropping, and copying images, but they always start out with 'pre-loaded' images.  I have modeled my code after theirs, where appropriate.
    Here is my code:
              //this gets called when the user clicks a button to 'look for a disk file'
                private function setPhoto():void
                    //create the FileReference instance
                    _fileRef = new FileReference();
                    _fileRef.addEventListener(Event.SELECT, onFileSelected);
                    //listen for the file has been opened
                    _fileRef.addEventListener(Event.COMPLETE, onFileLoaded);
                    var arr:Array = [];
                    arr.push(new FileFilter("Images", ".gif;*.jpeg;*.jpg;*.png"));
                    _fileRef.browse(arr); //then let go and let the event handlers deal with the result...
                private function onFileSelected(evt:Event):void
                    _fileRef.load(); //the result of the 'load' will be handled by the 'complete' handler
                private function onFileLoaded(evt:Event):void
                    var tempLoader:Loader = new Loader();
                    tempLoader.loadBytes(_fileRef.data);
                    tempLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoaderComplete);
                    //imgPhoto.source = _fileRef.data;  //this would work just fine, though, it wouldn't be cropped
                private function onLoaderComplete(event:Event):void
                    var loaderInfo:LoaderInfo = LoaderInfo(event.target);
                    var loadBD:BitmapData = new BitmapData(loaderInfo.width,loaderInfo.height);
                    //ok, now that we have the 'original' file in the bitmap data, we can crop it and then later resize it
                    //so, we need a 'square' of image cropped out of the original
                    //so...first we get a square of the 'full size' image
                    //if the image is taller than wide, we will take a square as wide as the image, and as tall as it is wide, starting 5% down from the top
                    //if the image is wider than tall, we will take a square as tall as the image, and as wide as it is tall, from the horizontal middle
                    var curW:int = loadBD.width;
                    var curH:int = loadBD.height;
                    var cropX:int = 0;
                    var cropY:int = 0;
                    var cropW:int = curW;
                    var cropH:int = curH;
                    var needCrop:Boolean = true; //default is to crop
                    var croppedBD:BitmapData;
                    if (curH > curW)
                        cropY = Math.round(curH * .05); //start at 5% down
                        cropH = cropW;
                    else if (curW > curH)
                        cropX = Math.round(curW/2) - Math.round(curH/2); //start at the middle, go 'back' by half the height
                        cropW = cropH;
                    else
                        needCrop = false; //it's already a square!  nothing to do (aside from the resize)
                    if (needCrop)
                        croppedBD = new BitmapData(cropW, cropH); //at this point it is 'empty', so fill it up
                        var fillPoint:Point = new Point(0,0); //since we're gonna fill into the top, left pixel on down and over
                        var fillRect:Rectangle = new Rectangle(cropX,cropY,cropW,cropH);
                        croppedBD.copyPixels(loadBD,fillRect,fillPoint);
                    else
                        croppedBD = loadBD;
                    imgPhoto.source = new Bitmap(croppedBD);  //this produces a properly sized, but blank-white image
    And here is the mxml for the image:
    <mx:Image id="imgPhoto" x="40" y="126" maxWidth="200" maxHeight="200" />
    Thanks!
    -David

    Hi,
    You were close to the solution.
    In "onLoaderComplete(event:Event):void", at the begining you create a BitmapData called "loadBD", you just forgot to fill it with the content from the loaderInfo.
    private function onLoaderComplete(event:Event):void {
         var loaderInfo:LoaderInfo = LoaderInfo(event.target);
         var loadBD:BitmapData = new BitmapData(loaderInfo.width,loaderInfo.height);
         loadBD.draw(loaderInfo.content);
    Kind regards,
    Mich

  • Image Resizer and Uploader

    I am new to Flex, and I have (so far) only developed two
    other applications using Flex.
    I am having a really difficult time with this issue. I've
    tried everything (except for creating a class) that I can think of
    to resolve this issue, and I'm running out of ideas.
    What I am trying to do is create an AIR application that
    takes the selected images and resizes them to a specified maximum
    height and width. It is resizing the image and saving it in a
    temporary spot, but it will not upload after it saves it. I keep
    receiving the error below:
    quote:
    Error #2044: Unhandled IOErrorEvent:. text=Error #2038: File
    I/O Error.
    at flash.filesystem::File/resolveComponents()
    at flash.filesystem::File/resolvePath()
    at ImageUploader/saveAndUploadImage()[C:\Documents and
    Settings\jgosselin\workspace\ImageUploader\src\ImageUploader.mxml:136]
    at ImageUploader/uploadButton_click()[C:\Documents and
    Settings\jgosselin\workspace\ImageUploader\src\ImageUploader.mxml:50]
    at ImageUploader/__uploadButton_click()[C:\Documents and
    Settings\jgosselin\workspace\ImageUploader\src\ImageUploader.mxml:213]
    My guess is that there is a lock on the file while it is
    being written and it tries to upload it before it closes. However,
    (as shown in the code) that is not the case. The error references
    to lines that has nothing to do with the line of code that is
    causing the issue. I have stepped through the code and it stops
    after the FileStream close event handler has been executed. What am
    I missing? What is it that I am not seeing? Has anyone developed
    something similar to this application? As shown in the code, I am
    using a series of events that triggers the next step of the
    process.
    EDIT: The code below is a scaled-down version of the
    application.

    Here is the code:
    quote:
    <?xml version="1.0" encoding="utf-8"?>
    <mx:WindowedApplication xmlns:mx="
    http://www.adobe.com/2006/mxml"
    xmlns:local="SmoothImage.as" layout="vertical" horizontalGap="0"
    verticalGap="0" paddingLeft="8" paddingRight="8" paddingTop="8"
    paddingBottom="8" width="640" height="480" xmlns:local1="*">
    <mx:Script>
    <![CDATA[
    import flash.events.OutputProgressEvent;
    import flash.events.ProgressEvent;
    import flash.filesystem.File;
    import flash.filesystem.FileStream;
    import flash.net.FileReference;
    import flash.net.URLRequest;
    import mx.collections.ArrayCollection;
    import mx.controls.Alert;
    import mx.graphics.codec.JPEGEncoder;
    [Bindable] private var filesFiltered:Array;
    private var maxImageWidth:Number = 640;
    private var maxImageHeight:Number = 480;
    private var tempFile:Array;
    private var currentFile:Number;
    private function uploadButton_click(event:Event):void
    tempFile = fileThumb.selectedItems;
    currentFile = 0;
    saveAndUploadImage(tempFile[currentFile]);
    private function
    uploadFile_progress(event:ProgressEvent):void
    var bytesUploaded:Number = event.bytesLoaded;
    var bytesTotal:Number = event.bytesTotal;
    uploadProgress.setProgress(bytesUploaded, bytesTotal);
    uploadProgress.label = "Uploaded: " +
    Math.round((bytesUploaded / bytesTotal) * 100) + "%";
    private function uploadFile_complete(event:Event):void
    uploadProgress.setProgress(0, 1);
    uploadProgress.label = "";
    if (currentFile + 1 < tempFile.length)
    currentFile++;
    saveAndUploadImage(tempFile[currentFile]);
    private function
    newFileStream_progress(event:OutputProgressEvent):void
    var bytesPending:Number = event.bytesPending;
    var bytesTotal:Number = event.bytesTotal;
    var percentage:Number = Math.round(100 - ((bytesPending /
    bytesTotal) * 100));
    uploadProgress.setProgress(percentage, 100);
    uploadProgress.label = "Writing: " + percentage + "%";
    if (bytesPending == 0) { event.target.close(); }
    private function newFileStream_close(event:Event):void
    var uploadURL:URLRequest = new URLRequest("
    http://localhost:8080/customers/propertypanorama_com/fileupload.php");
    var uploadFile:FileReference =
    FileReference(tempFile[currentFile]);
    uploadFile.addEventListener(ProgressEvent.PROGRESS,
    uploadFile_progress);
    uploadFile.addEventListener(Event.COMPLETE,
    uploadFile_complete);
    uploadFile.upload(uploadURL, "uploadFile");
    uploadProgress.setProgress(0, 1);
    uploadProgress.label = "";
    private function loader_complete(event:Event):void
    var loader:Loader = Loader(event.target.loader);
    var originalWidth:Number = event.target.width;
    var originalHeight:Number = event.target.height;
    var originalBitmap:BitmapData = new
    BitmapData(originalWidth, originalHeight, false, 0x000000);
    originalBitmap.draw(loader.content, null, null, null, null,
    true);
    var newImage:BitmapData = resizeImage(originalBitmap);
    var newFileStream:FileStream = new FileStream();
    newFileStream.addEventListener(OutputProgressEvent.OUTPUT_PROGRESS,
    newFileStream_progress);
    newFileStream.addEventListener(Event.CLOSE,
    newFileStream_close);
    newFileStream.openAsync(tempFile[currentFile],
    FileMode.WRITE);
    var jpgEncode:JPEGEncoder = new JPEGEncoder();
    var writeData:ByteArray = jpgEncode.encode(newImage);
    newFileStream.writeBytes(writeData, 0, writeData.length);
    private function saveAndUploadImage(originalImage:File):void
    var fromOldExt:String = originalImage.name;
    var toJPG:String;
    if (originalImage.extension.length == 4)
    toJPG = fromOldExt.substring(0, fromOldExt.length - 4) +
    "jpg";
    else
    toJPG = fromOldExt.substring(0, fromOldExt.length - 3) +
    "jpg";
    tempFile[currentFile] =
    File.applicationStorageDirectory.resolvePath(toJPG);
    var loader:Loader = new Loader();
    loader.contentLoaderInfo.addEventListener(Event.COMPLETE,
    loader_complete);
    loader.load(new URLRequest(originalImage.nativePath));
    private function
    resizeImage(originalImage:BitmapData):BitmapData
    var originalWidth:Number = originalImage.width;
    var originalHeight:Number = originalImage.height;
    var doResize:Boolean = false;
    var scaleRatio:Number = 1;
    var newImageMatrix:Matrix;
    var newImage:BitmapData;
    var newWidth:Number = 0;
    var newHeight:Number = 0;
    doResize = (originalWidth > maxImageWidth ||
    originalHeight > maxImageHeight);
    if (doResize)
    if (originalWidth > maxImageWidth)
    scaleRatio = maxImageWidth / originalWidth;
    newWidth = originalWidth * scaleRatio;
    newHeight = originalHeight * scaleRatio;
    else
    scaleRatio = maxImageHeight / originalHeight;
    newWidth = originalWidth * scaleRatio;
    newHeight = originalHeight * scaleRatio;
    newImageMatrix = new Matrix();
    newImageMatrix.scale(scaleRatio, scaleRatio);
    newImage = new BitmapData(newWidth, newHeight, false,
    0x000000);
    newImage.draw(originalImage, newImageMatrix, null, null,
    null, true);
    newImageMatrix = null;
    return newImage;
    else
    return originalImage;
    ]]>
    </mx:Script>
    <mx:HBox width="100%" horizontalAlign="right"
    paddingLeft="2" paddingRight="2" paddingTop="2" paddingBottom="2"
    verticalAlign="middle">
    <mx:ProgressBar id="uploadProgress" label="" width="100%"
    />
    <mx:Button id="uploadButton" label="Upload"
    click="uploadButton_click(event);" />
    </mx:HBox>
    </mx:WindowedApplication>

  • Local image resize and upload

    Hi guys,
    I've been checking around the net for a way to implement the following:
    user wants to upload a large image. the image is resized locally on their computer to a 60kb small image. this image is then uploaded and used.
    Is there a way to do this with flash? or what is the best method? (NB: I'm not interested in using Java)
    thanks for any info or links.
    Jeff

    Well in short, you need a second language to support that,
    e.g. PHP/ASP/CF.
    First you'll have to build a GUi in which you can upload the
    jpg, putting it to the server using php/asp/cf, then you'll need to
    make a call to that image, (importing it into your flex), then
    you'll have to set the parameters for the resizing, then you'll
    have to call a php/asp/cf script which does te resizing

  • Images resized and exif stripped when emailed ?

    Does any know why the iPhone resizes images (to 640x480) and strips out EXIF data when you email a photo. However, if you download the photos you get the full size and EXIF data ?
    As i often like to email photos direct to Flickr from my iphone it is very annoying to end up with a poorer image than what i should have.

    Hello All,
    Great news for the Apple iPhone.
    Just downloaded 2.1 software update, and the Geotagging correctly geotags the southern hemisphere, now adds a GPS Time-Stamp as well as the GPS longitude & latitude info to the EXIF.
    AND, when you e-mail it or transmit the image to a secure server, mobleme, Flickr . . . ALLL OF THE EXIF DATA STAYS INTACT, INCLUDING THE GPS METATAGS . . .
    AND THE SIZE OF THE IMAGE HAS BEEN REDUCED FROM 1200 X 1600 TO 600 X 800 . . .

  • Image Resizing and Folio Renditions

    Hello!
    I'm building a pretty large app, and I'm concerned about the size of some of my larger images.
    A. Is it typical to build both 1024x768 and 2048x1536 renditions? Or should I just build the 1024x768 and size my full page images for the 2048x1536? Or will it automatically view them at 72dpi?
    B. If I do build both renditions, can I keep the two different layouts in the same file with alternate layout? Or would I have to build a separate folio like I would for the iPhone?
    C. What is the best format to save images in? I've always saved as jpgs, but if I'm able to save as a gif or png for file size, I'd prefer to do that. But I don't want to compromise the integrity of the photo either.
    Thank you!

    Depending on the format of your files, you need not go into JAI. You may be able to do what you want with ImageIO.
    You just need to load the image, select the part you want, then check the length to width ratio to make sure it is appropriate, if not, then adjust it as such.
    If you want to get a 100, 100 thumb from a 1024, 768 image you can do this:
    BufferedImage bi = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = bi.createGraphics();
    g.drawImage(my1024x768, 0, 12, 100, 75, Color.BLACK, null);
    g.dispose();please note, that to get 1024 shunk up to 100, you need to divide by 10.24, when you do the same to the height of the image, you get 75, this leaves 25 pixels--so I centered the image at 12.
    to save the thumb in JPG:
    File f = new File(myFileNameAndPath);
    f.createFile();
    ImageIO.write(bi, "JPEG", f);**WARNING** untested code.

  • Render is resizing and cropping photos

    I am putting together a video montage for a mission trip that I did over the summer to Roatan honduras. whenever i render my sequence it scales the pictures to about 75 when in order to view the entire picture it should be around 23. Why does this happen? Also, it crops it all funky. PLEASE HELP ME I NEED THIS PROJECT DONE IN ABOUT 12 hours!

    You must set the scale in the Motion Tab for each image. This is very basic FCP stuff when working with any media that is not the precise same dimensions as your sequence settings. It si the default behavior.
    Forget your deadline. You should have started a few days ago.
    You might be able to make your deadline by using iPhoto's slide show mode but I don't use iPhoto.
    bogiesan

  • My FCP X automatically added a resize and crop effect to my entire movie, how can I get rid of it?

    My FCP X will not let me cut nor copy a section and paste it any where.  What can I do?
    Also, while trying to do this, it added a reshaoe little red box to my entire 90 minute feature film.  How can I get rid of this effect?  Have no idea how it can just show up like that when I never asked it to???

    My FCP X will not let me cut nor copy a section and paste it any where.  What can I do?
    You'll have to tell us exactly what you;re doing and what happens when you do it? Maybe post some screen shots?
    Also, while trying to do this, it added a reshaoe little red box to my entire 90 minute feature film.  How can I get rid of this effect?  Have no idea how it can just show up like that when I never asked it to???
    Screenshot? What are you copying from where? And where are you pasting to?

  • Image resizing and interpolation plugin

    A friend reports that genuine factals plugin is a part of Photoshop CS3. I note that a plugin for Photoshop (version not given) is advertised for sale by OnOneSoftware.
    Any comments appreciated.

    The GF plug-in is not part of Photoshop, you buy it from OnOne Software.
    John

  • PSE-6.....Image Resizing vs. Cropping

    I'm confused as to whether I should use the image resizing tool or the cropping tool. (my situation explained below)  Can someone explain the difference and what I should do?  But please note that I am TOTALLY new to photography and photoshop, and so I really need someone to explain it to me keeping in mind that I'm photography ignorant/illiterate.
    SITUATION:  I'm taking pictures of my handmade jewelry. I plan on doing several different things with the photos--printing, posting online, and emailing.
    From what I've read, these 3 actions require different sizes and resolutions (?).....But I've been told that printing requires 600 dpi (or ppi, right?)...........that posting online requires 72 ppi......that with emailing photo dimensions will be specified by the email recipient.      Upon uploading my pics began at 180 ppi and the actual size on the computer screen is GIGANTIC  (I assigned my camera the max 12 megapixels / 4000x3000-whatever that means).   So starting at 180 ppi how can I increase/decrease the ppi and which do I use (image resizing or cropping) for printing, posting online and emailing?
    Also, does changing the ppi (or dpi, right?) affect the size of the pic?  In other words, just how much related is ppi and size? example---can I have one picture that's 5x7 and another pictures that 8x10 but they have the same ppi?  And vice-verse?  As you can see I'm totally confused on this subject.
    Thank you to whomever responds.......I REALLY appreciate it.....

    Thanks Joe.  You are so helpful.  This stuff can be confusing to learn.  For example - below is a chart from an article I read about jewelry photography.  Notice next to "Resolution" the folders are referred to in "DPI"?  Did the author mean to say ppi?.....because my PSE-6 does not have any functions that allow DPI changes.....just ppi.....
    Recommended formats and file sizes for several categories of jewelry photography:
    Folder Name
    Master
    For Print
    For Home
    For Web
    Resolution
    600 DPI
    600 DPI
    300 DPI
    72 DPI
    File Format
    RAW
    PSD
    TIFF
    RAW
    TIFF
    RAW
    PSD
    TIFF
    JPEG
    Minimum Camera Size
    2-5 Megapixel
    5+ Megapixel
    2-5 Megapixel
    2 Megapixel

  • PSE5 Process Multiple Files Image Resize

    I want to batch convert some TIFF files to JPG and make them all 300 ppi. I tried suing the Multiple file processor in the Editor just entering 300 in resolution and leaving width & height blank. I hoped it would perform the same process as going to image resize and and changing resolution with resample and constrain proportions turned off. Instead it has changed the ppi from 72 to 300, but kept the size the same i.e. has added lots of extra pixels making the file enormous.
    The only way I can force it to shrink the image is to enter say 30cm as the width. The problem with this is twofold a) I have to trun all my photos so they are landscape b) if I have cropped a photo such that it doesn't have enough pixels to stretch then again it is getting resampled.
    Is this a limitation of PSE5 that wouldn't be there in CS3 or am I doing something wrong? I only want to print tham out 15x10 but read I should resize everything to 300 ppi. To be honest I never did this before I had PSE and they seemed to come out OK from a Canon that saves the files as default 72 ppi but large dimensions. Maybe someone couldexplain in laymans terms why the photos need to be resized to 300 ppi anyway? Thank you

    Well, you see, Process Multiple files is doing just what you asked it to do: it's
    resizing the photos. But you don't really want to resize the photos, just change the ppi setting. Is there a particular reason you want them to be 300ppi? PPI is a setting that only matters for printing or if you are sending a photo somewhere that requires that marker to be set to 300. Your camera doesn't know anything about ppi, only absolute pixel dimensions (eg 2480 x 1795 or whatever).
    When you go to print, however, your printer may prefer to have a higher pixel density, since it can play your pixels like an accordian: squash them closer together or spread them out thinner, depending on that ppi marker. The pixel density determines the inch/cm size of your print (at 72 ppi you'll get a print that's hugely bigger but less detailed; at 300 ppi a crisper smaller print.)
    I'm wondering why you would want to batch convert a whole big bunch of images at once, though. It would help if you would explain just what you want to do with the photos that requires the 300 ppi.

  • Why won't Photoshop revert to earlier history state after image resize when scripted?

    I've written an Applescript to automate watermarking and resizing images for my company. Everything generally works fine — the script saves the initial history state to a variable, resizes the image, adds the appropriate watermark, saves off a jpeg, then reverts to the initial history state for another resize and watermark loop.
    The problem is when I try not to use a watermark and only resize by setting the variable `wmColor` to `"None"` or `"None for all"`. It seems that after resizing and saving off a jpeg, Photoshop doesn't like it when I try to revert to the initial history state. This is super annoying, since clearly a resize should count as a history step, and I don't want to rewrite the script to implement multiple open/close operations on the original file. Does anyone know what might be going on? This is the line that's generating the problem (it's in both the doBig and doSmall methods, and throws an error every time I ask it just to do an image resize and change current history state):
                        set current history state of current document to initialState
    and here's the whole script:
    property type_list : {"JPEG", "TIFF", "PNGf", "8BPS", "BMPf", "GIFf", "PDF ", "PICT"}
    property extension_list : {"jpg", "jpeg", "tif", "tiff", "png", "psd", "bmp", "gif", "jp2", "pdf", "pict", "pct", "sgi", "tga"}
    property typeIDs_list : {"public.jpeg", "public.tiff", "public.png", "com.adobe.photoshop-image", "com.microsoft.bmp", "com.compuserve.gif", "public.jpeg-2000", "com.adobe.pdf", "com.apple.pict", "com.sgi.sgi-image", "com.truevision.tga-image"}
    global myFolder
    global wmYN
    global wmColor
    global nameUse
    global rootName
    global nameCount
    property myFolder : ""
    -- This droplet processes files dropped onto the applet
    on open these_items
      -- FILTER THE DRAGGED-ON ITEMS BY CHECKING THEIR PROPERTIES AGAINST THE LISTS ABOVE
              set wmColor to null
              set nameCount to 0
              set nameUse to null
              if myFolder is not "" then
                        set myFolder to choose folder with prompt "Choose where to put your finished images" default location myFolder -- where you're going to store the jpgs
              else
                        set myFolder to choose folder with prompt "Choose where to put your finished images" default location (path to desktop)
              end if
              repeat with i from 1 to the count of these_items
                        set totalFiles to count of these_items
                        set this_item to item i of these_items
                        set the item_info to info for this_item without size
                        if folder of the item_info is true then
      process_folder(this_item)
                        else
                                  try
                                            set this_extension to the name extension of item_info
                                  on error
                                            set this_extension to ""
                                  end try
                                  try
                                            set this_filetype to the file type of item_info
                                  on error
                                            set this_filetype to ""
                                  end try
                                  try
                                            set this_typeID to the type identifier of item_info
                                  on error
                                            set this_typeID to ""
                                  end try
                                  if (folder of the item_info is false) and (alias of the item_info is false) and ((this_filetype is in the type_list) or (this_extension is in the extension_list) or (this_typeID is in typeIDs_list)) then
      -- THE ITEM IS AN IMAGE FILE AND CAN BE PROCESSED
      process_item(this_item)
                                  end if
                        end if
              end repeat
    end open
    -- this sub-routine processes folders
    on process_folder(this_folder)
              set these_items to list folder this_folder without invisibles
              repeat with i from 1 to the count of these_items
                        set this_item to alias ((this_folder as Unicode text) & (item i of these_items))
                        set the item_info to info for this_item without size
                        if folder of the item_info is true then
      process_folder(this_item)
                        else
                                  try
                                            set this_extension to the name extension of item_info
                                  on error
                                            set this_extension to ""
                                  end try
                                  try
                                            set this_filetype to the file type of item_info
                                  on error
                                            set this_filetype to ""
                                  end try
                                  try
                                            set this_typeID to the type identifier of item_info
                                  on error
                                            set this_typeID to ""
                                  end try
                                  if (folder of the item_info is false) and (alias of the item_info is false) and ((this_filetype is in the type_list) or (this_extension is in the extension_list) or (this_typeID is in typeIDs_list)) then
      -- THE ITEM IS AN IMAGE FILE AND CAN BE PROCESSED
      process_item(this_item)
                                  end if
                        end if
              end repeat
    end process_folder
    -- this sub-routine processes files
    on process_item(this_item)
              set this_image to this_item as text
              tell application id "com.adobe.photoshop"
                        set saveUnits to ruler units of settings
                        set display dialogs to never
      open file this_image
                        if wmColor is not in {"None for all", "White for all", "Black for all"} then
                                  set wmColor to choose from list {"None", "None for all", "Black", "Black for all", "White", "White for all"} with prompt "What color should the watermark be?" default items "White for all" without multiple selections allowed and empty selection allowed
                        end if
                        if wmColor is false then
                                  error number -128
                        end if
                        if nameUse is not "Just increment this for all" then
                                  set nameBox to display dialog "What should I call these things?" default answer ("image") with title "Choose the name stem for your images" buttons {"Cancel", "Just increment this for all", "OK"} default button "Just increment this for all"
                                  set nameUse to button returned of nameBox -- this will determine whether or not to increment stem names
                                  set rootName to text returned of nameBox -- this will be the root part of all of your file names
                                  set currentName to rootName
                        else
                                  set nameCount to nameCount + 1
                                  set currentName to rootName & (nameCount as text)
                        end if
                        set thisDocument to current document
                        set initialState to current history state of thisDocument
                        set ruler units of settings to pixel units
              end tell
      DoSmall(thisDocument, currentName, initialState)
      DoBig(thisDocument, currentName, initialState)
              tell application id "com.adobe.photoshop"
                        close thisDocument without saving
                        set ruler units of settings to saveUnits
              end tell
    end process_item
    to DoSmall(thisDocument, currentName, initialState)
              tell application id "com.adobe.photoshop"
                        set initWidth to width of thisDocument
                        if initWidth < 640 then
      resize image thisDocument width 640 resample method bicubic smoother
                        else if initWidth > 640 then
      resize image thisDocument width 640 resample method bicubic sharper
                        end if
                        set myHeight to height of thisDocument
                        set myWidth to width of thisDocument
                        if wmColor is in {"White", "White for all"} then
                                  set wmFile to (path to resource "water_250_white.png" in bundle path to me) as text
                        else if wmColor is in {"Black", "Black for all"} then
                                  set wmFile to (path to resource "water_250_black.png" in bundle path to me) as text
                        end if
                        if wmColor is not in {"None", "None for all"} then
      open file wmFile
                                  set wmDocument to current document
                                  set wmHeight to height of wmDocument
                                  set wmWidth to width of wmDocument
      duplicate current layer of wmDocument to thisDocument
                                  close wmDocument without saving
      translate current layer of thisDocument delta x (myWidth - wmWidth - 10) delta y (myHeight - wmHeight - 10)
                                  set opacity of current layer of thisDocument to 20
                        end if
                        set myPath to (myFolder as text) & (currentName) & "_640"
                        set myOptions to {class:JPEG save options, embed color profile:false, quality:12}
      save thisDocument as JPEG in file myPath with options myOptions appending lowercase extension
                        set current history state of current document to initialState
              end tell
    end DoSmall
    to DoBig(thisDocument, currentName, initialState)
              tell application id "com.adobe.photoshop"
                        set initWidth to width of thisDocument
                        if initWidth < 1020 then
      resize image thisDocument width 1020 resample method bicubic smoother
                        else if initWidth > 1020 then
      resize image thisDocument width 1020 resample method bicubic sharper
                        end if
                        set myHeight to height of thisDocument
                        set myWidth to width of thisDocument
                        if wmColor is in {"White", "White for all"} then
                                  set wmFile to (path to resource "water_400_white.png" in bundle path to me) as text
                        else if wmColor is in {"Black", "Black for all"} then
                                  set wmFile to (path to resource "water_400_black.png" in bundle path to me) as text
                        end if
                        if wmColor is not in {"None", "None for all"} then
      open file wmFile
                                  set wmDocument to current document
                                  set wmHeight to height of wmDocument
                                  set wmWidth to width of wmDocument
      duplicate current layer of wmDocument to thisDocument
                                  close wmDocument without saving
      translate current layer of thisDocument delta x (myWidth - wmWidth - 16) delta y (myHeight - wmHeight - 16)
                                  set opacity of current layer of thisDocument to 20
                        end if
                        set myPath to (myFolder as text) & (currentName) & "_1020"
                        set myOptions to {class:JPEG save options, embed color profile:false, quality:12}
      save thisDocument as JPEG in file myPath with options myOptions appending lowercase extension
                        set current history state of current document to initialState
              end tell
    end DoBig

    As many others here I use JavaScript so I can’t really help you with your problem.
    But I’d like to point to »the lazy person’s out« – with many operations that result in creating a new file on disk I simply duplicate the image (and flatten in the same step) to minimize any chance of damaging the original file if the Script should not perform as expected.

Maybe you are looking for