imgtool.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. async def download_remote_img(url):
  21. """
  22. 下载远程图片
  23. """
  24. name = os.path.split(url)[-1]
  25. local_img = f"resource/{name}"
  26. async with aiohttp.request("GET", url) as r:
  27. content = await r.read()
  28. async with aiofiles.open(local_img, "wb") as f:
  29. await f.write(content)
  30. await f.close()
  31. return local_img
  32. # if __name__ == "__main__":
  33. # loop = asyncio.get_event_loop()
  34. # loop.run_until_complete(crop_img("/tmp/test.jpg", (10, 10, 300, 300)))