python实现图片等比例缩小

python PIL库实现图片等比例缩小,并由jpg格式转换为png格式图片

from PIL import Image
def resize_image(img_name_path,max_width=1500,max_height=800):
    """
    等比例缩小图片,并把jpg转为png格式
    :param img_name_path 图片路径
    :param max_width   缩小后的最大宽度
    :param max_height  缩小后的最大高度
    :return:
    """
    #获取原始尺寸图片
    image = Image.open(img_name_path)
    width = image.width  #获取图片原宽度
    height = image.height #获取图片原高度
    #宽度和高度有任意不符合我们给定的最大值,将缩小,否则直接转为png格式
    if max_width <= width or max_height <= height:
        #计算缩小比例
        ratio  = min(max_width/width,max_height/height)
        #计算缩小后的大小
        new_width = int(width * ratio)
        new_height = int(height * ratio)
        #使用PIL库中resize方法进行等比例缩小
        resize_img = image.resize((new_width,new_height),Image.ANTIALIAS)
        #保存更改之后的图片
        resize_img.save(img_name_path.replace('.jpg','.png'))
    else:
        image.save(img_name_path.replace('.jpg', '.png'))
if __name__ == '__main__':
    img_name = 'input.jpg'
    resize_image(img_name)
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
实现两个手指缩放图片,可以使用以下步骤: 1. 监听用户手指触摸事件并记录手指的位置,通常使用`onTouchEvent`方法实现。 2. 在用户操作过程中计算两个手指之间的距离(例如计算手指1和手指2之间的距离),以此来确定缩放比例。 3. 使用缩放比例来改变图片的大小,可以使用`ImageView`的`setScaleX`和`setScaleY`方法实现。 以下是一个简单的实现示例: ```python class MyImageView(ImageView): def __init__(self, context): super().__init__(context) self.last_x = 0 self.last_y = 0 self.last_distance = 0 def onTouchEvent(self, event): action = event.getAction() if action == MotionEvent.ACTION_DOWN: self.last_x = event.getX() self.last_y = event.getY() elif action == MotionEvent.ACTION_MOVE and event.getPointerCount() == 2: x1 = event.getX(0) y1 = event.getY(0) x2 = event.getX(1) y2 = event.getY(1) distance = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2) if self.last_distance == 0: self.last_distance = distance return True scale = distance / self.last_distance self.setScaleX(self.getScaleX() * scale) self.setScaleY(self.getScaleY() * scale) self.last_distance = distance elif action == MotionEvent.ACTION_UP or action == MotionEvent.ACTION_CANCEL: self.last_distance = 0 return True ``` 在这个示例中,我们首先记录手指按下的位置。在手指移动的过程中,我们计算两个手指之间的距离,并使用距离的变化来计算缩放比例。最后,我们使用缩放比例来改变图片的大小。注意,在手指抬起时,我们需要将`last_distance`重置为0,以便下一次缩放可以正确工作。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值