问题
I'm trying to use ImageMagick to create thumbnail images that are 3840 x 2160.
I need the image to have a black background and white text. The text should be centered vertically and horizontally.
I want to be able to set a font size, but if the text would extend off the image, automatically decrease the font size so it fits with some amount of padding on the left and right.
I will be doing this in bulk with several hundred thousand images. From what I've been able to find, it looks like you always have to set a font size and there's no way to make it dynamic.
Can anyone confirm if this is possible to do?
回答1:
You can set a size that specifies how large a space is available for your text and ImageMagick will choose the largest pointsize text that will fit:
magick -gravity center -background black -fill white -size 400x300 -font /System/Library/Fonts/MarkerFelt.ttc caption:"Short Text" short.png
magick -gravity center -background black -fill white -size 400x300 -font /System/Library/Fonts/MarkerFelt.ttc caption:"Somewhat longer text that will get rendered in a smaller font" long.png
If you want a margin around the text, you can set a maximum size for the text, then increase the size of the canvas with -extent
- I'll do that in red so you can see what the -extent
added:
magick -gravity center -background black -fill white -size 400x300 -font /System/Library/Fonts/MarkerFelt.ttc caption:"Somewhat longer text" -background red -extent 410x400 long.png
If you are reading lines from files to generate your hundreds of thousands of images, you can pipe the text in from another command like this:
echo -n "Text supplied by other command" | magick -gravity center -background black -fill white -size 400x300 -font /System/Library/Fonts/MarkerFelt.ttc caption:@- result.png
If you want to know what pointsize ImageMagick chose, you can get it like this:
magick identify -format "%[caption:pointsize]\n" result.png
59
来源:https://stackoverflow.com/questions/63042750/use-imagemagick-to-generate-image-from-text