Scales an image to the desired dimensions with pixel sampling. Unlike other scaling methods, this method does not introduce any additional color into the scaled image.
function sampleImage($image_path, $width, $height, $preshrink)
{
    $imagick = new \Imagick(realpath($image_path));

    if ($preshrink) {
        // Easier to see pixel when source image is tiny.
        $imagick->scaleImage(
            $imagick->getImageWidth() / 8,
            $imagick->getImageHeight() / 8
        );
    }

    $imagick->sampleImage($width, $height);
    header("Content-Type: image/jpeg");
    echo $imagick->getImageBlob();
}