imgtool.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. # -*- coding: utf-8 -*-
  2. import io
  3. import os
  4. import aiofiles
  5. import aiohttp
  6. from PIL import Image
  7. from utils.fileuploader import ossfile_uploader
  8. async def crop_img(orgimg, point=(), i=0):
  9. """
  10. 切割图片
  11. """
  12. img = Image.open(orgimg)
  13. region = img.crop(point)
  14. buf = io.BytesIO()
  15. region.save(buf, format="png")
  16. new_img = "resource/" + os.path.split(orgimg)[-1].replace(".", f"_{i}_crop.")
  17. remote_url = ossfile_uploader.upload_from_str(new_img, buf.getvalue(),
  18. {"Content-Type": "image/png"})
  19. return remote_url
  20. def crop_img_remote(orgimg, point=(), i=0):
  21. """
  22. 切割图片
  23. """
  24. img = Image.open(orgimg)
  25. region = img.crop(point)
  26. buf = io.BytesIO()
  27. region.save(buf, format="png")
  28. new_img = "resource/" + os.path.split(orgimg)[-1].replace(".", f"_{i}_crop.")
  29. remote_url = ossfile_uploader.upload_from_str(new_img, buf.getvalue(),
  30. {"Content-Type": "image/png"})
  31. return remote_url
  32. def crop_img_local(orgimg, point=()):
  33. """
  34. 切割图片
  35. """
  36. img = Image.open(orgimg)
  37. region = img.crop(point)
  38. new_img = "/tmp/" + os.path.split(orgimg)[-1].replace(".", "_crop.")
  39. region.save(new_img, format="png")
  40. return new_img
  41. async def download_remote_img(url):
  42. """
  43. 下载远程图片
  44. """
  45. name = os.path.split(url)[-1]
  46. local_img = f"/tmp/{name}"
  47. async with aiohttp.request("GET", url) as r:
  48. content = await r.read()
  49. async with aiofiles.open(local_img, "wb") as f:
  50. await f.write(content)
  51. await f.close()
  52. return local_img