简体   繁体   中英

How to resize an image by saving the resized version under a new name?

Thanks for being a part of this amazing community.
Here I've been fighting with my script and looks like I need a hint.

I have the following file structure:

Mother_Directory/
./child1_Directory
file1.jpg
file2.JPG
file3.jpg
./child2_Directory
file1.jpg
file2.JPG
file3.jpg
./child3_Directory
file1.jpg
file2.JPG
file3.jpg

Now I want to use imagemagick 's convert function to do all sorts of things (say resize) on these files in the child directories and save them in Mother_Directory_2/ (which is on an external hard drive) under a new name.
eg external_HD_path/Mother_Directory_2/child2_Directory/resized_file1.jpg .

Here is my code:

for f in `find . -name "*.*"`; do convert $f -resize 50% ../Mother_Directory_2/$f; done

this one was supposed to save the new files in ../Mother_Directory_2/ ,
but no luck (even without name-change logic). I tend to believe that what I'm trying to achieve is something trivial but I've no idea where to look for a hint. Is there a simple way to do it?

I believe the issue is with the way you are using $f in the destination directory. The $f usually will contain the full path of the file that is being converted. Instead you can try using "basename" in the script.

for f in `find . -name "*.*"`; do base=$(basename "$f") ; convert $f -resize 50% ../Mother_Directory_2/$base; done

Given that many people search for this solution here i would like to post the easiest solution i've managed to write based on all the comments and posts i've went through.

step 1. create all the folders in the new Mother_Directory_2 (get the names of the folders from the original Mother_Directory)

for d in */ ; do mkdir ~/Desktop/Mother_Directory_2/$d; done

step 2.
2.1.get the child directory names by using
parentname="$(basename "$(dirname "$f")")"
2.2. get the filenames by using
base=$(basename "$f")
3.3 Run the script below (cd Mother_Directory)

for f in `find . -name "*.*"`; do base=$(basename "$f") ; parentname="$(basename "$(dirname "$f")")"; convert -resize 1000x1000  ./$parentname/$base ../Mother_Directory_2/$parentname/resize_$base; done

hope this would be helpful - if you are a Bash specialist please suggest a more efficient way of doing the same. thanks again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM