Angular 5, get colors from an image

2020-07-29 02:17发布

I have an android app that uses android.support.v7.graphics.Palette to get the color info from a dynamic image and then customize the layout of the activity to use mutated colors from the image. My question is, does Angular 5 have anything similiar? I want to model the web version of this project as closely to the android version as possible. This would mean dynamically setting a few style colors after an image is selected.

Update: I have been looking at ColorThief() for javascript. But I am not sure how to access it from an Angular 5 component.

Thank you PK

1条回答
做个烂人
2楼-- · 2020-07-29 03:03

For anyone looking for something like this I ended up using node-vibrant.js. I ran npm install then added the file to my scripts array in the angular.json file

"scripts": [
  "node_modules/node-vibrant/dist/vibrant.min.js"
]

Then I changed my tsconfig.json file to the following:

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "allowSyntheticDefaultImports": true,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "module": "commonjs",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ]
  },
  "allowJs": true
}

I then imported Vibrant and Palette into my angular 6.0.0 component

import Vibrant from 'node-vibrant';
import { Palette } from 'node-vibrant/lib/color';

Then it was pretty easy to call in ngOnInit() with just an url to an image

getVibrantColor(url: string){
  // Using builder
  Vibrant.from(url).getPalette((err, palette) => {
    console.log(palette)
    this.palette = palette;
  });

}

styleContainer(): any {
  console.log('palette', this.palette);
  if (this.palette.LightVibrant) {
    return { 'background-color': this.palette.LightVibrant.getHex(), 'border-color': 
      this.palette.LightMuted.getHex(), 'color': '#000000' };
  } else {
    return { 'background-color': '#FFFFFF', 'border-color':        
       this.palette.LightMuted.getHex(), 'color': '#000000' };
  }

}

And call it from the html file:

<div *ngIf="palette" class="col-lg-8 details-top-container" 
[ngStyle]="styleContainer()"></div>

The hardest part was getting the proper import statement.

import * as Vibrant from 'node-vibrant';

would not work as the documentation says it will.

Hope this saves someone some time.

PK

查看更多
登录 后发表回答