001/* 002 * Copyright (c) 2023-2026, Agents-Flex (fuhai999@gmail.com). 003 * <p> 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * <p> 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * <p> 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package com.agentsflex.core.model.image; 017 018import com.agentsflex.core.model.client.HttpClient; 019import com.agentsflex.core.util.IOUtil; 020import com.agentsflex.core.util.StringUtil; 021 022import java.io.File; 023import java.util.Arrays; 024import java.util.Base64; 025 026public class Image { 027 028 /** 029 * The base64-encoded JSON of the generated image 030 */ 031 private String b64Json; 032 033 /** 034 * The URL of the generated image 035 */ 036 private String url; 037 038 /** 039 * The data of image 040 */ 041 private byte[] bytes; 042 043 public static Image ofUrl(String url) { 044 Image image = new Image(); 045 image.setUrl(url); 046 return image; 047 } 048 049 public static Image ofBytes(byte[] bytes) { 050 Image image = new Image(); 051 image.setBytes(bytes); 052 return image; 053 } 054 055 public String getB64Json() { 056 return b64Json; 057 } 058 059 public void setB64Json(String b64Json) { 060 this.b64Json = b64Json; 061 } 062 063 public String getUrl() { 064 return url; 065 } 066 067 public void setUrl(String url) { 068 this.url = url; 069 } 070 071 public byte[] getBytes() { 072 return bytes; 073 } 074 075 public void setBytes(byte[] bytes) { 076 this.bytes = bytes; 077 } 078 079 public byte[] readBytes() { 080 return bytes; 081 } 082 083 public void writeToFile(File file) { 084 if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) { 085 throw new IllegalStateException("Can not mkdirs for path: " + file.getParentFile().getAbsolutePath()); 086 } 087 if (this.bytes != null && this.bytes.length > 0) { 088 IOUtil.writeBytes(this.bytes, file); 089 } else if (this.b64Json != null) { 090 byte[] bytes = Base64.getDecoder().decode(b64Json); 091 IOUtil.writeBytes(bytes, file); 092 } else if (StringUtil.hasText(this.url)) { 093 byte[] bytes = new HttpClient().getBytes(this.url); 094 IOUtil.writeBytes(bytes, file); 095 } 096 } 097 098 @Override 099 public String toString() { 100 return "Image{" + 101 "b64Json='" + b64Json + '\'' + 102 ", url='" + url + '\'' + 103 ", bytes=" + Arrays.toString(bytes) + 104 '}'; 105 } 106}