Consider an image (img) as

enter image description here

The dimension of the image is:

{w, h} = ImageDimensions[img]

{488, 275}

I want to change the dimension to the power of 2, which comes very next to the highest dimension (488) i.e. 512.

How can I do this?

Edit 1:

I am manually trying to do this using

Image[ArrayPad[ImageData[img], {a, b}]]

But cannot figure out the suitable values for a and b.

  • $\begingroup$ Try ImageResize $\endgroup$ – Ulrich Neumann Jan 31 '18 at 11:48
  • $\begingroup$ @UlrichNeumann I don't want to resize the image because it will distort the shape of the different features. $\endgroup$ – Majis Jan 31 '18 at 11:49
  • $\begingroup$ Ok! ImageCrop[img] gives an image of size 255x259 (nearby 256) $\endgroup$ – Ulrich Neumann Jan 31 '18 at 11:54
  • $\begingroup$ ... ImageCrop[img,{256,256}] $\endgroup$ – Ulrich Neumann Jan 31 '18 at 12:02

Take the image dimensions and calculate the log with base 2. Then take the Ceiling to get the next best exponent that is large or equal to it and use ImageCrop:

img = Import["https://i.stack.imgur.com/yzWZx.png"]
ImageCrop[img, 2^(Ceiling[Log[2, #]] & /@ ImageDimensions[img])]

Mathematica graphics


There is an inbuilt function ImagePad to do this.


{wdesired, hdesired} = 2^Ceiling[Log[2, #]] & /@ ImageDimensions[img]

(Thanks to @halirutan)

This will give me the desired dimensions.


ImagePad[img, {{Ceiling[(wdesired - w)/2], 
   Floor[(wdesired - w)/2]}, {Ceiling[(hdesired - h)/2], 
   Floor[(hdesired - h)/2]}}]

gives me my desired image.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.