4

RailsアプリでDragonflyを使用してサムネイル画像を生成しています。

すべての画像をJPGとして提供しています。クライアントは、次のような透明な PNG ファイルをアップロードしています。

http://www.ibanez.co.jp/products/images/eg2010/ART120_TRF_12_02.png

Dragonfly は RMagick を使用してこれらの画像を JPG に変換します。問題は、PNG 画像を黒い背景の JPG に変換することであり、私のサイトのデザインには白い背景が必要です。私はこのようにそれをオーバーライドしようとしました:

encoded_image = Magick::Image.from_blob(image.data).first

if encoded_image.format.downcase == format
  image # do nothing
else
  encoded_image.format = format
  encoded_image.background_color = "white"
  encoded_image.transparent_color = "white"
  encoded_image.to_blob
end

しかし、生成された JPG 画像にはまだ黒い背景が含まれています。透明レイヤーを変換するときにRMagickを打ち負かして白い背景を使用する方法を知っている人はいますか?

PNG として提供できることはわかっていますが、その場合、画像は 10 倍の大きさになり、サイトはすでにかなりの帯域幅を使用しています。

4

2 に答える 2

10

ImageList を作成して、元の画像と同じサイズの白い画像を透明な画像の下に置くことができます。ImageList を画像にフラット化すると、透明色が 2 番目の画像に含まれているものに置き換えられた画像が得られます。

img_list = Magick::ImageList.new
img_list.read("my_png_file.png")
img_list.new_image(img_list.first.columns, img_list.first.rows) { self.background_color = "white" } # Create new "layer" with white background and size of original image
image = img_list.reverse.flatten_images

これは私にとってはうまくいきますが、さらに最適化できると思います。

それが役立つことを願っています! ヘンドリック

于 2010-09-01T16:03:36.947 に答える
0

他の誰かが同じ問題を抱えている場合、RMagick を使用してこれを行う方法を理解できませんでした。コマンドライン ImageMagick (convert) を使用してソリューションを作成しました。

  if encoded_image.format.downcase == "png"
    temp_file = Tempfile.new(image.object_id)

    encoded_image.write("png:" + temp_file.path)

    encoded_image.destroy!

    system "convert -flatten \"#{temp_file.path}\" \"jpg:#{temp_file.path}\""

    encoded_image = Magick::Image.read(temp_file.path)[0]

    temp_file.delete
  else
于 2010-06-03T11:46:09.433 に答える