Save images on mobile from online source unity
I tried to convert it to bytes editing the function too rather than passing it www.text and got an image corrupt error
That's probably the cause of 90% of your problem. WWW.text
is used for non binary data such as simple text.
1.Download images or files with WWW.bytes
not WWW.text
.
2.Save image with File.WriteAllBytes
.
3.Read image with File.ReadAllBytes
.
4.Load image to Texture with Texture2D.LoadImage(yourImageByteArray);
5.Your path must be Application.persistentDataPath/yourfolderName/thenFileName
if you want this to be compatible with every platform. It shouldn't be Application.persistentDataPath/yourFileName
or Application.dataPath
.
6.Finally, use Debug.Log
to see what's going on in your code. You must or at-least use the debugger. You need to know exactly where your code is failing.
You still need to perform some error checking stuff.
public void downloadImage(string url, string pathToSaveImage)
{
WWW www = new WWW(url);
StartCoroutine(_downloadImage(www, pathToSaveImage));
}
private IEnumerator _downloadImage(WWW www, string savePath)
{
yield return www;
//Check if we failed to send
if (string.IsNullOrEmpty(www.error))
{
UnityEngine.Debug.Log("Success");
//Save Image
saveImage(savePath, www.bytes);
}
else
{
UnityEngine.Debug.Log("Error: " + www.error);
}
}
void saveImage(string path, byte[] imageBytes)
{
//Create Directory if it does not exist
if (!Directory.Exists(Path.GetDirectoryName(path)))
{
Directory.CreateDirectory(Path.GetDirectoryName(path));
}
try
{
File.WriteAllBytes(path, imageBytes);
Debug.Log("Saved Data to: " + path.Replace("/", "\\"));
}
catch (Exception e)
{
Debug.LogWarning("Failed To Save Data to: " + path.Replace("/", "\\"));
Debug.LogWarning("Error: " + e.Message);
}
}
byte[] loadImage(string path)
{
byte[] dataByte = null;
//Exit if Directory or File does not exist
if (!Directory.Exists(Path.GetDirectoryName(path)))
{
Debug.LogWarning("Directory does not exist");
return null;
}
if (!File.Exists(path))
{
Debug.Log("File does not exist");
return null;
}
try
{
dataByte = File.ReadAllBytes(path);
Debug.Log("Loaded Data from: " + path.Replace("/", "\\"));
}
catch (Exception e)
{
Debug.LogWarning("Failed To Load Data from: " + path.Replace("/", "\\"));
Debug.LogWarning("Error: " + e.Message);
}
return dataByte;
}
Usage:
Prepare url to download image from and save to:
//File url
string url = "http://www.wallpapereast.com/static/images/Cool-Wallpaper-11C4.jpg";
//Save Path
string savePath = Path.Combine(Application.persistentDataPath, "data");
savePath = Path.Combine(savePath, "Images");
savePath = Path.Combine(savePath, "logo");
As you can see, there is no need to add the image extension(png, jpg) to the savePath and you shouldn't add the image extension in the save path. This will make it easier to load later on if you don't know the extension. It should work as long as the image is a png or jpg image format.
Dowload file:
downloadImage(url, savePath);
Load Image from file:
byte[] imageBytes = loadImage(savePath);
Put image to Texture2D:
Texture2D texture;
texture = new Texture2D(2, 2);
texture.LoadImage(imageBytes);
@Programmer 's answer is correct but it's obsolete I just update it:
WWW is obsolete
The UnityWebRequest is a replacement for Unity’s original WWW object. It provides a modular system for composing HTTP requests and handling HTTP responses. The primary goal of the UnityWebRequest system is to permit Unity games to interact with modern Web backends. It also supports high-demand features such as chunked HTTP requests, streaming POST/PUT operations and full control over HTTP headers and verbs. https://docs.huihoo.com/unity/5.4/Documentation/en/Manual/UnityWebRequest.html
UnityWebRequest.GetTexture is obsolete
Note: UnityWebRequest.GetTexture is obsolete. Use UnityWebRequestTexture.GetTexture instead.
Note: Only JPG and PNG formats are supported.
UnityWebRequest properly configured to download an image and convert it to a Texture.
https://docs.unity3d.com/ScriptReference/Networking.UnityWebRequestTexture.GetTexture.html
using System;
using System.Collections;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
public class ImageDownloader : MonoBehaviour
{
private void Start()
{
//File url
string url = "https://www.stickpng.com/assets/images/58482b92cef1014c0b5e4a2d.png";
//Save Path
string savePath = Path.Combine(Application.persistentDataPath, "data");
savePath = Path.Combine(savePath, "Images");
savePath = Path.Combine(savePath, "logo.png");
downloadImage(url,savePath);
}
public void downloadImage(string url, string pathToSaveImage)
{
StartCoroutine(_downloadImage(url,pathToSaveImage));
}
private IEnumerator _downloadImage(string url, string savePath)
{
using (UnityWebRequest uwr = UnityWebRequestTexture.GetTexture(url))
{
yield return uwr.SendWebRequest();
if (uwr.isNetworkError || uwr.isHttpError)
{
Debug.LogError(uwr.error);
}
else
{
Debug.Log("Success");
Texture myTexture = DownloadHandlerTexture.GetContent(uwr);
byte[] results = uwr.downloadHandler.data;
saveImage(savePath, results);
}
}
}
void saveImage(string path, byte[] imageBytes)
{
//Create Directory if it does not exist
if (!Directory.Exists(Path.GetDirectoryName(path)))
{
Directory.CreateDirectory(Path.GetDirectoryName(path));
}
try
{
File.WriteAllBytes(path, imageBytes);
Debug.Log("Saved Data to: " + path.Replace("/", "\\"));
}
catch (Exception e)
{
Debug.LogWarning("Failed To Save Data to: " + path.Replace("/", "\\"));
Debug.LogWarning("Error: " + e.Message);
}
}
byte[] loadImage(string path)
{
byte[] dataByte = null;
//Exit if Directory or File does not exist
if (!Directory.Exists(Path.GetDirectoryName(path)))
{
Debug.LogWarning("Directory does not exist");
return null;
}
if (!File.Exists(path))
{
Debug.Log("File does not exist");
return null;
}
try
{
dataByte = File.ReadAllBytes(path);
Debug.Log("Loaded Data from: " + path.Replace("/", "\\"));
}
catch (Exception e)
{
Debug.LogWarning("Failed To Load Data from: " + path.Replace("/", "\\"));
Debug.LogWarning("Error: " + e.Message);
}
return dataByte;
}
}