1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
| private inputElement; private imageUrl; private creatorInput() { this.inputElement = document.createElement('input'); this.inputElement.type = 'file'; this.inputElement.accept = 'image/*'; this.inputElement.style.display = 'none'; document.body.appendChild(this.inputElement); this.inputElement.addEventListener('change', (event: Event) => { const target = event.target as HTMLInputElement; if (target.files && target.files.length > 0) { const file = target.files[0]; this.handleFileUpload(file); } }); } private handleFileUpload(file: File) { if (file.size > 1024 * 1024) { console.error('文件过大,无法上传'); return; } const reader = new FileReader(); reader.onload = (e) => { const imageUrl = e.target?.result as string; Tool.compressImage(imageUrl, 126, 126).then((compressedImageUrl) => { this.imageUrl = compressedImageUrl; Tool.loadTextureInCocos(this.imgNode, compressedImageUrl, 126, 126); }); }; reader.readAsDataURL(file); }
private loadTextureInCocos(node: Node, imageUrl: string){ let image = new Image(); image.onload = () => { let img = new ImageAsset(image) let texture = new Texture2D(); texture.image = img; let spriteFrame = new SpriteFrame(); spriteFrame.texture = texture; node.getComponent(Sprite).spriteFrame = spriteFrame; node.getComponent(UITransform).setContentSize(width, hight); }; image.src = imageUrl; }
public compressImage(url: string, targetWidth: number, targetHeight: number): Promise<string> { return new Promise((resolve) => { const img = new Image(); img.src = url;
img.onload = () => { const width = img.width; const height = img.height;
const size = Math.min(width, height);
const startX = (width - size) / 2; const startY = (height - size) / 2;
const canvas = document.createElement('canvas'); canvas.width = size; canvas.height = size;
const ctx = canvas.getContext('2d'); ctx?.drawImage(img, startX, startY, size, size, 0, 0, size, size);
const scaledCanvas = document.createElement('canvas'); scaledCanvas.width = targetWidth; scaledCanvas.height = targetHeight; const scaledCtx = scaledCanvas.getContext('2d');
scaledCtx?.drawImage(canvas, 0, 0, size, size, 0, 0, targetWidth, targetHeight);
resolve(scaledCanvas.toDataURL('image/jpeg', 0.5)); }; }); } public loadTextureInCocos(node: Node, imageUrl: string, width, hight) { let image = new Image(); image.onload = () => { let img = new ImageAsset(image) let texture = new Texture2D(); texture.image = img; let spriteFrame = new SpriteFrame(); spriteFrame.texture = texture; node.getComponent(Sprite).spriteFrame = spriteFrame; node.getComponent(UITransform).setContentSize(width, hight); }; image.src = imageUrl; }
private clickBtn(){ this.inputElement.click(); }
|