css - 背景圖片在 Angular 中不顯示
是的,我有搜尋過並找到很多例子,但都對我無效。我不確定自己哪裡做錯了。需要幫助!
如果我使用 <img> 標籤,我可以看到圖片,但當我作為 background-image 使用時就看不到。不過當我檢查元素時,我可以看到二進位圖片。
嘗試在 stackblitz 上做一個範例 https://stackblitz.com/edit/display-image-from-rest-api-qpnspq?embed=1&file=src/app/app.component.ts
HTML:
<!-- This works -->
<div class="row" style="max-width: 100%; margin-left: 1px;" >
<img id="dashboardImage" [src]='imageBlobDataUrl' height='500' width='500' />
</div>
<!-- This does NOT works -->
<div class="row" style="max-width: 100%; margin-left: 1px;" [style.background-image]="image"> </div>
TS :
@Input() imageBlobDataUrl: any;
selectedImage: QiImage = new QiImage();
public header:SafeHtml;
public content:SafeHtml[];
public image:SafeStyle;
constructor(
private qiImageService: QiImageService,
private sanitizer: DomSanitizer,
private imageService: ImageService
) {}
populateImageDetails(lineId, bitmapFileName) {
this.imageService
.populateImageDetails(lineId, bitmapFileName)
.subscribe( (selectedImage : any) => {
this.selectedImage = selectedImage;
//let TYPED_ARRAY = new Uint8Array(selectedImage.imageData);
//const STRING_CHAR = String.fromCharCode.apply(null, TYPED_ARRAY);
//let base64String = btoa(STRING_CHAR);
let objectURL = 'data:image/png;base64,' + selectedImage.imageData;
this.imageBlobDataUrl = this.sanitizer.bypassSecurityTrustUrl(objectURL);
this.image = this.sanitizer.bypassSecurityTrustStyle(`url(${objectURL})`);
});
}
答案#1
當我嘗試你的 Stackblitz 時,它運作正常。你需要修正 CSS 才能在視圖中顯示圖片。
不要對樣式 URL 使用 bypassSecurityTrustUrl。因此下面的縮圖用法是無效的:
this.thumbnail = this.sanitizer.bypassSecurityTrustUrl(objectURL); // Do NOT Use
this.image = this.sanitizer.bypassSecurityTrustStyle(`url(${objectURL})`); // This works fine and is Valid
嘗試調整你的圖片的 CSS 位置,它就會顯示出來:
<div class="row"
style="width: 100%; height: 100%; position:absolute;
margin-left: 1px; background-repeat: no-repeat;"
[style.background-image]="image"> </div>
答案#2
如果你嘗試用 CSS 設置背景圖片?像這樣:
.bg {
background-image: url("../../yourimage");
height: 100%;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
display: flex;
justify-content: center;
align-items: center;
}
在模板中,您可以使用綁定來隨意設置 CSS 類別
