LoginSignup
0
4

More than 5 years have passed since last update.

画像サイズを自動で取得する

Last updated at Posted at 2017-04-04

PostCSS Assets

個人的にはまず以下のようなmixinを用意して・・・

mixin/_image.scss
// postCss Assets
@mixin image($url, $density: 1, $scale:1){
 @include hide-txt(); // 画像の説明テキストを表示しない自前mixin
 $scale: 1 / $scale;
  background-repeat: no-repeat;
  background-position: center center;
  background-image: resolve($url);
  background-size: size($url,$density * $scale);
  width: width($url,$density * $scale);
  height: height($url,$density * $scale);
}
// SPをベースにしてPCも同じ画像のケース
@mixin same-image($url, $scale:1){
  $scale: 1 / $scale;
  @include image($url,1 * $scale);
  @include mq(sp) { // sp環境用の自前mixin
    @include image($url,2 * $scale);
  }
}
style.scss
.sample{
  @include same-image('sample1.png');
  // SP用に640*480の画像があると仮定
  // PC -> 640*480
  // SP -> 320*240
}

上記のような1行を書くだけで、
画像サイズを自動で取得した上で、
PC、SP環境に対応したスタイルを、
キャッシュバスター付きで当てることができる。

Gulpの設定はこんな感じ↓

gulpfile.js

.pipe(postcss([assets({
  basePath: `${DEST}`, // プロジェクトで公開するパス
  loadPaths: [`img/`], // basePathから見た画像フォルダの位置
  relative: `css/`, // img/とcss/の相対的な位置
  cachebuster: true,
  // baseUrl: '',
})]))

Compass

画像のサイズを測るだけならCompassでもok

Compass(Sass)で画像サイズを自動取得する

0
4
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
0
4