5

現在、ブロブストアを使用して画像のサムネイルを生成していますが、サムネイルのサイズをimgタグに保存することをお勧めします。これは良い習慣であり、レンダリングを高速化し、部分的に読み込まれたページの見栄えを良くするのに役立ちます。

元の画像のサイズしかわからない場合、ブロブストアによって生成されたサムネイルのサイズを計算するにはどうすればよいですか?

私の以前の試みはあまり正確ではなく、ほとんどの場合、1 ピクセルか 2 ピクセルずれていました (おそらく丸めのため)。

サムネイルを取得し、画像 API を使用して寸法を確認するよりもうまくいくことは理解していますが、それは非効率的だと思います。

現時点で計算に使用するコードは次のとおりです。ただし、1 ピクセルずれている場合があり、ブラウザーが画像をわずかに引き伸ばして、アーティファクトのサイズを変更したり、パフォーマンスを低下させたりします。

from __future__ import division
def resized_size(original_width, original_height, width, height):
    original_ratio = float(original_width) / float(original_height)
    resize_ratio = float(width) / float(height)
    if original_ratio >= resize_ratio:
        return int(width), int(round(float(width) / float(original_ratio)))
    else:
        return int(round(float(original_ratio) * float(height))), int(height)

精度は非常に重要です。

4

2 に答える 2

4

I see the problem. The reason is that C's rint is being used to calculate the dimensions. Python does not have an equivalent rint implementation as it was taken out by Rossum in 1.6:

http://markmail.org/message/4di24iqm7zhc4rwc

Your only recourse right now is to implement your own rint in python.

rint by default does a "round to even" vs pythons round which does something else. Here is a simple implementation (no edge case handling for +inf -inf, etc.)

import math

def rint(x):
  x_int = int(x)
  x_rem = x - x_int  # this is problematic
  if (x_int % 2) == 1:
    return round(x)
  else:
    if x_rem <= 0.5:
      return math.floor(x)
    else:
      return math.ceil(x)

上記のコードは、理論的に実装する方法です。問題は x_rem にあります。x - x_int は分数コンポーネントを取得する必要がありますが、代わりに分数 + デルタを取得できます。したがって、必要に応じてしきい値を追加することができます

import math

def rint(x):
  x_int = int(x)
  x_rem = x - x_int
  if (x_int % 2) == 1:
    return round(x)
  else:
    if x_rem - 0.5 < 0.001:
      return math.floor(x)
    else:
      return math.ceil(x)

こっち。0.001 のしきい値をハードコーディングしました。しきい値処理自体に問題があります。rint の実装を実際に試して、アプリケーションに合わせて、何が最適かを確認する必要があると思います。幸運を!

于 2011-02-28T20:08:26.560 に答える
0

1600x1200 の元の画像があり、サイズ 800 のサムネイルを取得したい場合、期待される結果は 800x600 の画像です。これを計算するには、次のようにします。

// In Java
double aspectRatio = originalWidth / originalHeight;
output_width = 800;
output_height = (int)Math.round(800.0 / aspectRatio);

これが退化したケースで機能するかどうか見てみましょう。145x111 のオリジナルがあり、サイズ 32 のサムネイルを取得したいとします。

aspectRatio == 1.3063063063063063
output_width == 32
output_height == Math.round(32.0 / 1.3063063063063063) == 24

縦向きの画像でも同様のことができます。

于 2011-02-26T01:39:33.093 に答える