简体   繁体   中英

Resize/crop image encoded as base64 image string

in my case, there are 2 ways of getting image to resize/crop.

  1. upload normal image file
  2. giving base64 string data of image

in 1. case, resize and crop is working well:

f = Image.open(uploaded_image)
new_width, new_height = 1200, 630
wpercent = (new_width / float(f.size[0]))
hsize = int((float(f.size[1]) * float(wpercent)))

if f.mode != "RGB":
   f = f.convert('RGB')

og_img = None
if f.size[0] < new_width:
  #upscale
  og_img = f.resize((new_width, hsize), Image.BICUBIC)

elif f.size[0] >= new_width:
  #downscale
  og_img = f.resize((new_width, hsize), Image.ANTIALIAS)

og_img = og_img.crop((0, 0, 1200, 630))

resized/cropped image: 在此输入图像描述

in 2. case, the code is the same as above with slight change in:

base64_image = str(request.POST.get('base64_image')).split(',')[1]
imgfile = open('/'.join([settings.MEDIA_ROOT, 'test.png' ]), 'w+b')
imgfile.write(decodestring(base64_image))
imgfile.seek(0)
f = Image.open(imgfile)

#.. as above

but the resized/cropped image: 在此输入图像描述

why is it in 2.case bad in quality and size? (black bottom part..) what am I doing wrong? am I reading the base64 string in wrong way?

I found a website which has many interesting things in it.It has 2(there are many) tools which maybe can help you.The 1th tool converts image to base64 and the 2th tool minifies the size of image (up to 70% save).

http://www.w3docs.com/tools/minimage/

http://www.w3docs.com/tools/image-base64

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM