def rectangle_to_square(rectangle, width, height):
    """
    Converts a rectangle in the image, to a valid square. Keeps the original
    rectangle centered whenever possible, but when that requires going outside
    the original picture, it moves the square so it stays inside.

    Assumes the square is able to fit inside the original picture.
    """
    from_x, from_y, to_x, to_y = rectangle

    rectangle_width = to_x - from_x
    rectangle_height = to_y - from_y
    size = max(rectangle_width, rectangle_height)

    x_center = from_x + rectangle_width // 2
    y_center = from_y + rectangle_height // 2

    from_x = x_center - size // 2
    to_x = x_center + size // 2
    from_y = y_center - size // 2
    to_y = y_center + size // 2

    # ensure fitting horizontally
    if from_x < 0:
        to_x = to_x - from_x
        from_x = 0
    elif to_x > width:
        from_x = from_x - (to_x - width)
        to_x = width

    # ensure fitting vertically
    if from_y < 0:
        to_y = to_y - from_y
        from_y = 0
    elif to_y > height:
        from_y = from_y - (to_y - height)
        to_y = height

    return from_x, from_y, to_x, to_y