Reputation: 121
I am trying to resize and compress images that are uploaded from my django app before it is uploaded to google cloud storage. I tried using firebase to resize any image that is uploaded automatically, but it gives giving resize error. I would like my django app to do this compression first before it is uploaded to google cloud. The standard pillow compression doesn't work on cloud storages. How can accomplish this?
Take the view function below, how would i make resize the image before upload?
if request.method == 'POST':
form = GalleryForm(request.POST, request.FILES)
if form.is_valid():
image = form.save(commit=False)
image.user = usr
image.save()
return HttpResponseRedirect(reverse('profile-detail', args=(), kwargs={'slug': slug}))
Right now, my app would upload the image (Whatever Size) to Google Cloud, then open the image, resize it, and overwrite the originally uploaded image. I feel this might put strain on my app processes eventually. I would like my app to just resize the image before uploading. Below is my code I use to resize images after uploading.
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
img_read = storage.open(self.image.name, 'r')
img = Image.open(img_read)
if img.height > 801 or img.width > 534:
output_size = (801, 534)
img.thumbnail(output_size)
in_mem_file = io.BytesIO()
img.save(in_mem_file, format='JPEG')
img_write = storage.open(self.image.name, 'w+')
img_write.write(in_mem_file.getvalue())
img_write.close()
img_read.close()
Another draw back to this would be that, the image has to be in 'JPEG' format for this to work. I am looking for a better way to get this done.
Upvotes: 1
Views: 1142
Reputation:
Since you mentioned using pillow, this code should help with resizing:
from PIL import Image
im = Image.open(r"1.png")
width, height = im.size
# reduce to 30% of the original size
target_size_percent = 30
new_width = int(width * target_size_percent / 100)
new_height = int(height * target_size_percent / 100)
new_size = (new_width, new_height)
im1 = im.resize(new_size)
im1.show()
im1.save('resized.png')
If you have a fixed target size, you can change the new_width and new_height variables to match those sizes. Just make sure you maintain the aspect ratio of the images, if at all possible.
Upvotes: 1
Reputation: 347
(trying to answer even though there is a lack of information)
you can use OpenCV for resizing:
import cv2
img = cv2.imread('/home/img/image_path', cv2.IMREAD_UNCHANGED)
print('Original Dimensions : ',img.shape)
scale_percent = 60 # percent of original size
width = int(img.shape[1] * scale_percent / 100)
height = int(img.shape[0] * scale_percent / 100)
dim = (width, height)
# resize image
resized = cv2.resize(img, dim, interpolation = cv2.INTER_AREA)
Upvotes: 0