Samir
Samir

Reputation: 419

PHP uploading images in the correct dimensions

I know this question is very common but the main point in my question is that i want to know how facebook or some other websites upload their pictures in the correct size. for example. if we upload a picture of the dimension : width : 1000px , height : 20px. then facebook updates the status updates with that pic but makes the image size small in the correct ratio. its jus scales down the picture but we can know that the image is very widthy (my own word for very high width :P) where as long heighty pictures are also posted in the correct proportion.

PIC NUMBER 1

PIC NUMBER 2

I have included the image examples above. how does facebook calculate the size n ratio of the pics and echo out the pic by keeping the right dimensions but scaling it down at the same time.

Upvotes: 0

Views: 261

Answers (2)

Scuzzy
Scuzzy

Reputation: 12332

This code is fairly verbose, but might give you an idea on how to calculate image dimensions.

Parameters are your source width and your target maximum resize width and heights

function image_resize_dimensions($source_width,$source_height,$thumb_width,$thumb_height)
{
  $source_ratio = $source_width / $source_height;
  $thumb_ratio = $thumb_width / $thumb_height;

  // Ratio is Taller
  if ($thumb_ratio > $source_ratio)
  {
    $result_height = $thumb_height;
    $result_width = $thumb_height * $source_ratio;
  }

  // Ratio is Wider
  elseif ($thumb_ratio < $source_ratio)
  {
    $result_width = $thumb_width;
    $result_height = $thumb_width / $source_ratio;
  }

  // Ratio the Same
  elseif($thumb_ratio == $source_ratio)
  {
    $result_height = $thumb_height;
    $result_width = $thumb_width;
  }

  return array('x'=>$result_width,'y'=>$result_height);

}

Upvotes: 1

sascha
sascha

Reputation: 4690

I think there are a few factors.

  1. the main factor is the width of the content the image is displayed in
  2. the original width of the image
  3. whether you want to fill the whole content with the image or not (Facebook doesn't)

Let's say you have an image which has a width of 1000px. Your content is 400px. You want to fill the content a half with your image, so you have an end width of 200px for your image. The height is just ca percental calculation (rule of three).

In the end, you will have the correct ratio and it fits well in your content.

Of course you could also check whether the image is 16:9 or 4:3 to determine the max width for images like your first example.

Upvotes: 0

Related Questions