import tensorflow as tf
def resize_function(img_path,save_path):
img = tf.io.read_file(img_path)
# 解码图片
# img = tf.image.decode_png(img,channels=3) # RGBA,PNG
img = tf.image.decode_jpeg(img,channels=3) # RGBA,jpg
hight = img.shape[0]
width = img.shape[1]
print('original shape:',img.shape)
img = tf.image.resize(img,[int(hight*0.5),int(width*0.5)])
print('resized shape:',img.shape)
# 转换张量数据类型
img = tf.cast(img, dtype=tf.uint8)
# 编码为图片
# img = tf.image.encode_png(img) # PNG
img = tf.image.encode_jpeg(img) # jpeg
# 保存图片
with tf.io.gfile.GFile(save_path,'wb') as file:
file.write(img.numpy())
# img_path = 'C:/Users/a/Downloads/dog.png' # PNG格式
img_path = 'C:/Users/a/Downloads/001.jpg' # JPEG格式
save_path = img_path[:-4]+'_resize.jpg' # 要保存为的图片
resize_function(img_path,save_path)