1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PlayFrameworkで画像をインライン化

Last updated at Posted at 2017-04-17

PlayFrameworkで画像をインライン化

リクエスト数課金があるプロダクトを利用するため、CSS Spliteを導入していないWEBサイトの費用が嵩みそうなので、imgタグのsrcをbase64エンコードした画像データに変更してリクエスト数を減らす。


package helpers

import org.apache.commons.codec.binary.Base64
import com.google.common.io.ByteStreams

object AssetObj {
  def imageBase64(path: String, ext: String = "png") = {
    try {
      val url = this.getClass().getClassLoader().getResource(s"public/${path}")
      val is = url.openStream()
      try {
        val arr = ByteStreams.toByteArray()
        getBase64(arr, ext)
      } finally {
        is.close()
      }
    } catch {
      case e: Exception => routes.Assets.at(path).toString
    }
  }
  protected def getBase64(source: Array[Byte], ext: String) = {
    val img = new String(Base64.encodeBase64(source))
    s"data:image/${ext};base64,${img}"
  }
}

viewで下記のように使える。


<img src="@helpers.AssetObj.imageBase64("images/test.png")" alt="test" />
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?