diff --git a/src/main/java/utils/FileUtilities.java b/src/main/java/utils/FileUtilities.java index 2c754cc..044204a 100644 --- a/src/main/java/utils/FileUtilities.java +++ b/src/main/java/utils/FileUtilities.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; @@ -54,6 +55,25 @@ public static String getEncodedString(File image) { } } + /** + * Saves a Base64-encoded string as an image file in the specified directory. + * + * @param base64String The Base64-encoded string representing the image. + * @param outputFile The file where the image should be saved. + * @throws RuntimeException if an IOException occurs during file writing. + */ + public static void saveDecodedImage(String base64String, File outputFile) { + try { + // Decode the Base64 string to a byte array + byte[] imageBytes = Base64.getDecoder().decode(base64String); + // Write the byte array to the specified file + Files.write(outputFile.toPath(), imageBytes); + } catch (IOException e) { + // Wrap IOException in a RuntimeException and throw it + throw new RuntimeException(e); + } + } + /** * Retrieves the Base64-encoded string representation of an image file from the given file path. * @@ -438,6 +458,7 @@ public static class Json { public JSONObject urlsJson = new JSONObject(); public JSONObject notificationJson = new JSONObject(); private final Printer log = new Printer(Json.class); + private static final Gson gson = new Gson(); /** * Saves a JSON object to a file. @@ -603,5 +624,27 @@ public static String formatJsonString(String json) { catch (IOException e) {e.printStackTrace();} return null; } + + /** + * Converts a given input object to another type using Gson serialization/deserialization. + * + * @param The target class type. + * @param input The input object to be converted. + * @param tClass The target class type to convert into. + * @return An instance of the target class {@code T} populated with data from the input object, or null if conversion fails. + */ + public static T typeConversion(Object input, Class tClass) { + return gson.fromJson(getJsonString(input), tClass); + } + + /** + * Converts a given input object to its JSON string representation using Gson. + * + * @param input The input object to be serialized into JSON. + * @return A JSON string representing the input object, or null if the input is null. + */ + public static String getJsonString(Object input) { + return gson.toJson(input); + } } }