Update trim_image.py

add option to adjust aspect ratio
This commit is contained in:
unkn0w7n 2024-10-05 13:42:50 +05:30
parent 927f45e1cd
commit 501a9b2fc9

View File

@ -7,12 +7,18 @@ __copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
import os
import sys
from qt.core import QCheckBox, QDialog, QDialogButtonBox, QFormLayout, QHBoxLayout, QIcon, QKeySequence, QLabel, QSize, QSpinBox, Qt, QToolBar, QVBoxLayout
from qt.core import QCheckBox, QDialog, QDialogButtonBox, QFormLayout, QHBoxLayout, QIcon, QKeySequence, QLabel, QSize, QSpinBox, QDoubleSpinBox, Qt, QToolBar, QVBoxLayout
from calibre.gui2 import gprefs
from calibre.gui2.tweak_book.editor.canvas import Canvas
def reduce_to_ratio(w, h, t):
h = min(h, w / t)
w = t * h
return int(w), int(h)
class Region(QDialog):
ignore_value_changes = False
@ -30,6 +36,12 @@ class Region(QDialog):
h.setRange(20, max_height), h.setSuffix(' px'), h.setValue(height)
h.valueChanged.connect(self.value_changed)
l.addRow(_('&Height:'), h)
self.ratio_input = r = QDoubleSpinBox(self)
r.setRange(0.0, 5.00), r.setDecimals(2), r.setValue(max_width/max_height), r.setToolTip('For example, use 0.75 for kindle devices.')
self.m_width = max_width
self.m_height = max_height
r.valueChanged.connect(self.aspect_changed)
l.addRow(_('&Adjust Aspect Ratio:'), r)
self.const_aspect = ca = QCheckBox(_('Keep the ratio of width to height fixed'))
ca.toggled.connect(self.const_aspect_toggled)
l.addRow(ca)
@ -46,6 +58,16 @@ class Region(QDialog):
self.resize(self.sizeHint())
self.current_aspect = width / height
def aspect_changed(self):
inp = float(self.ratio_input.value())
if inp > 0 and inp != round(self.m_width/self.m_height, 2):
rw, rh = reduce_to_ratio(self.m_width, self.m_height, inp)
self.width_input.setValue(rw)
self.height_input.setValue(rh)
else:
self.width_input.setValue(self.m_width)
self.height_input.setValue(self.m_height)
def const_aspect_toggled(self):
if self.const_aspect.isChecked():
self.current_aspect = self.width_input.value() / self.height_input.value()