Unity material rendering using script working incorrectly - c#

This is the hierarchy of Button component.
Button
Image
Text
The script used for rendering is as follows:
for(int ii = 0; ii < idlist.Count; ii++){
GameObject addTypeButton = (GameObject)Instantiate(prefabButton);
addTypeButton.transform.SetParent(ParentPanel, false);
var mybutton = addTypeButton.GetComponent<MyButton>();
//set text
mybutton.text.text = (string)sometext[ii];
//get image
WWW www = new WWW((string)someImageUrl[ii]);
yield return www;
//set image
var b64_bytes = System.Convert.FromBase64String(www.text);
Texture2D tex = new Texture2D(1, 1, TextureFormat.RGB24, false);
tex.EncodeToPNG();
tex.LoadImage(b64_bytes);
//yield return new WaitForSeconds (5) ;
mybutton.image.material.mainTexture = tex;
//testing
File.WriteAllBytes(Application.dataPath + "/../Saved["+ii +"].png", b64_bytes);
}
Testing command generates proper images in the sequence.
However, in Unity the image is rendered on the next object.
Here's the Screenshot
Where exactly I am going wrong?

Don not use WWW.text to load images. This is what WWW.bytes is there for. So, your System.Convert.FromBase64String(www.text); should be removed. You also don't need the Texture2D.EncodeToPNG(); function here since the image you are downloading is already in png or jpeg format. Just save the downloaded image bytes directly.
Finally, if you want your saving stuff to work on every platform, you have to use Application.persistentDataPath instead of Application.dataPath. You should also use Path.Combine to concatenate paths instead of doing it manually.
for (int ii = 0; ii < idlist.Count; ii++)
{
GameObject addTypeButton = (GameObject)Instantiate(prefabButton);
addTypeButton.transform.SetParent(ParentPanel, false);
var mybutton = addTypeButton.GetComponent<MyButton>();
//set text
mybutton.text.text = (string)sometext[ii];
//get image
WWW www = new WWW((string)someImageUrl[ii]);
yield return www;
//set image
byte[] downloadedImage = www.bytes;
Texture2D tex = new Texture2D(1, 1, TextureFormat.RGB24, false);
tex.LoadImage(downloadedImage);
//yield return new WaitForSeconds (5) ;
mybutton.image.material.mainTexture = tex;
//testing
string savePath = Application.persistentDataPath;
savePath = Path.Combine(savePath, "images");
savePath = Path.Combine(savePath, ii.ToString());
savePath = Path.Combine(savePath, ".png");
File.WriteAllBytes(savePath, downloadedImage);
}

Related

Unity Upload Image To Server With Codeigniter Not Working

I want to upload an image jpg to my server. I have try but it didn't work.
I don't what cause the upload failed.
Below the detail code.
Unity C#
public void TakePicture(int maxSize)
{
if (NativeCamera.IsCameraBusy())
{
Debug.Log("Camera Busy");
return;
}
else
{
NativeCamera.Permission permission = NativeCamera.TakePicture((path) =>
{
Debug.Log("Image path: " + path);
if (path != null)
{
// Create a Texture2D from the captured image
Texture2D texture = NativeCamera.LoadImageAtPath(path, maxSize);
//snap.SetPixels(tex.GetPixels());
byte[] bytes = File.ReadAllBytes(path);
Debug.Log("Bytes:" + bytes);
Destroy(texture);
StartCoroutine(upload_ocr_image(bytes));
if (texture == null)
{
Debug.Log("Couldn't load texture from " + path);
return;
}
// Assign texture to a temporary quad and destroy it after 5 seconds
GameObject quad = GameObject.CreatePrimitive(PrimitiveType.Quad);
quad.transform.position = Camera.main.transform.position + Camera.main.transform.forward * 2.5f;
quad.transform.forward = Camera.main.transform.forward;
quad.transform.localScale = new Vector3(1f, texture.height / (float)texture.width, 1f);
Material material = quad.GetComponent<Renderer>().material;
if (!material.shader.isSupported) // happens when Standard shader is not included in the build
material.shader = Shader.Find("Legacy Shaders/Diffuse");
material.mainTexture = texture;
Destroy(quad, 5f);
// If a procedural texture is not destroyed manually,
// it will only be freed after a scene change
Destroy(texture, 5f);
}
}, maxSize);
Debug.Log("Permission result: " + permission);
}
}
IEnumerator upload_ocr_image(byte[] bytes)
{
// UtilityScript.GetComponent<utility>().Sand_Clock_Loading(true);
// yield return new WaitForSeconds(2.5f);
WWWForm formDate = new WWWForm();
formDate.AddField("frameCount", Time.frameCount.ToString());
formDate.AddBinaryData("ocr_image", bytes, "ocr.jpg", "image/jpg");
formDate.AddField("phone_code", "+61");
formDate.AddField("phone_number", "434599859");
using (UnityWebRequest www = UnityWebRequest.Post(web_url.url_upload_ocr_image, formDate))
{
yield return www.Send();
//UtilityScript.GetComponent<utility>().Sand_Clock_Loading(false);
if (www.isNetworkError)
{
Debug.Log(www.error);
// UtilityScript.GetComponent<utility>().MessageBox_Check_Connection();
}
else
{
Debug.Log(www.downloadHandler.text);
}
}
}
And this the code in server codeigniter php.
function upload_ocr_image()
{
$phone_code = $this->input->post('phone_code', true);
$phone_number = $this->input->post('phone_number', true);
$allowedType = array(IMAGETYPE_GIF,IMAGETYPE_JPEG,IMAGETYPE_PNG);
$imgType = exif_imagetype($_FILES['ocr_image']['tmp_name']);
if(!in_array($imgType,$allowedType))
{
echo "Images Type Error. Images Type Only : GIF , JPEG, PNG";
exit;
}
else
{
//upload original size front end slider
$config['upload_path'] = './assets/ocr_image/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['file_name'] = $phone_code.$phone_number;
$config['overwrite'] = FALSE;
$config['max_size'] = '8096';
$config['max_width'] = '6000';
$config['max_height'] = '6000';
$this->load->library('upload', $config);
if(!$this->upload->do_upload("ocr_image"))
{
echo "Maximum File Size Only 2 Mb Or Max Width = 2000 , Height = 2000";
exit;
}
else
{
$img_data = $this->upload->data();
// Create Thumbnail
/*
$magicianObj = new imageLib("assets/ocr_image/".$img_data["file_name"].$phone_code.$phone_number);
$magicianObj -> resizeImage(80, 80, 0, true);
$magicianObj -> saveImage("assets/admin/img/photos/".$img_data["raw_name"]."_thumb".$img_data["file_ext"], 100);
$next_id = $next_id.$img_data["file_ext"];
$thumb_name = $img_data["raw_name"]."_thumb".$img_data["file_ext"];
$data = array("photo_name"=>$next_id,
"thumb_photo_name"=>$thumb_name,
"create_date"=>date("Y-m-d H:i:s"));
$this->db->insert("gallery_tbl",$data);
*/
}
}
}
No error found. But it always failed.
This line of code in codeigniter PHP :
if(!$this->upload->do_upload("ocr_image"))
Always return true.
How it work ?, How to upload the picture with proper way ?
Edited :
I use an asset native camera android and ios from unity to take a picture from camera.
Thank You
simply add initialize $this->upload->initialize($config); after
$this->load->library('upload', $config); and check, also check upload directory path is right ? and directory permission
Finally i found the problem.
Just set allowed type extension to except all extension in codeigniter upload file.
change :
$config['allowed_types'] = 'gif|jpg|png|jpeg';
to
$config['allowed_types'] = '*';

convert Pdf to png create Black margin around image

I'm trying to convert pdf to image with ghostscript.net (1.2.1.0) and gs version is 9.22 x86.
my code:
using (_rasterizer = new GhostscriptRasterizer())
{
_rasterizer.Open(inputPdfPath, _lastInstalledVersion, false);
//_rasterizer.CustomSwitches.Add("-sDEVICE=pngalpha");
//_rasterizer.CustomSwitches.Add("-dTextAlphaBits=4");
//_rasterizer.CustomSwitches.Add("-dGraphicsAlphaBits=4");
for (int pageNumber = 1; pageNumber <= _rasterizer.PageCount; pageNumber++)
{
var desiredDPI = 102;
using (System.Drawing.Image img = _rasterizer.GetPage(desiredDPI, desiredDPI, pageNumber))
{
img.Save(pageNumber + ".png", ImageFormat.Png);
}
}
}
it works for some pages, but for some images, it create black margin and black background.
sample files:
pdf => png
I test with gs command, it was ok.
I tried following code. images was good but text was low quality.
public Image getImg(string inputFile, int pageNO, int resolution)
{
GhostscriptPngDevice dev = new GhostscriptPngDevice(GhostscriptPngDeviceType.PngAlpha);
dev.GraphicsAlphaBits = GhostscriptImageDeviceAlphaBits.V_4;
dev.TextAlphaBits = GhostscriptImageDeviceAlphaBits.V_4;
dev.ResolutionXY = new GhostscriptImageDeviceResolution(resolution, resolution);
dev.InputFiles.Add(inputFile);
dev.Pdf.FirstPage = pageNO;
dev.Pdf.LastPage = pageNO;
dev.CustomSwitches.Add("-dDOINTERPOLATE");
dev.OutputPath = pageNO + ".png";
dev.Process();
return Image.FromFile(pageNO + ".png");
}
GhostscriptPngDevice dev = new GhostscriptPngDevice(GhostscriptPngDeviceType.Png16m);
dev.GraphicsAlphaBits = GhostscriptImageDeviceAlphaBits.V_4;
dev.TextAlphaBits = GhostscriptImageDeviceAlphaBits.V_4;
dev.BackgroundColor = Color.White;
dev.ResolutionXY = new GhostscriptImageDeviceResolution(desired_x_dpi, desired_y_dpi);
dev.InputFiles.Add(inputPathAndFile);
dev.Pdf.FirstPage = 1;
dev.Pdf.LastPage = 1;
dev.CustomSwitches.Add("-dDOINTERPOLATE");
dev.OutputPath = outputPathAndFile;
dev.Process();

Reduce PDF size using iTetstSharp in .Net

I am converting number of Jpeg or Png image to PDF using iTextSharp dll. I can convert but the size of the PDF cause much worry. If I convert 9 jpeg images (total size is 4.5 MB) into single pdf , it creates 12.3 MB size of PDF. Below is conversion part.
private bool CreatePdf(string stFilePath_in, List<ImageData> lstImageData_in, string doctype, string stproCompid)
{
bool flag = false;
StringBuilder builder = new StringBuilder();
try
{
this.UtilityProgress(lstImageData_in.Count);
builder.Append(stFilePath_in);
builder.Append(#"\");
builder.Append(lstImageData_in[0].Barcode);
builder.Append(".pdf");
Document document = new Document(PageSize.LETTER, 10f, 10f, 42f, 35f);
PdfWriter.GetInstance(document, new FileStream(builder.ToString(), FileMode.OpenOrCreate));
document.Open();
IOrderedEnumerable<ImageData> enumerable = from files in lstImageData_in
orderby files.PageNo
select files;
if (enumerable != null)
{
DbFileData data2;
foreach (ImageData data in enumerable)
{
Bitmap bitmap = new Bitmap(data.FilePath);
iTextSharp.text.Image instance = iTextSharp.text.Image.GetInstance(bitmap, ImageFormat.Png);
if (instance.Height > instance.Width)
{
float num = 0f;
num = 700f / instance.Height;
instance.ScalePercent(num * 100f);
}
else
{
float num2 = 0f;
num2 = 540f / instance.Width;
instance.ScalePercent(num2 * 100f);
}
instance.Border = 15;
instance.BorderColor = BaseColor.BLACK;
instance.BorderWidth = 3f;
document.Add(instance);
document.NewPage();
bitmap.Dispose();
}
document.Close();
if (doctype == "AR")
{
//data2.m_stInvoiceNo = lstImageData_in[0].Barcode.Substring(2);
data2.m_stInvoiceNo = lstImageData_in[0].Barcode.ToString();
data2.m_doctype = "AR";
}
else
{
data2.m_stInvoiceNo = lstImageData_in[0].Barcode.ToString();
data2.m_doctype = "PO";
}
data2.m_stImgLocation = builder.ToString();
string str = DateTime.Now.ToString("MM/dd/yy,hh:mm:ss");
data2.m_dtDate = DateTime.Now.Date;
data2.m_stTime = str.Substring(str.IndexOf(",") + 1);
data2.m_stcompid = stproCompid;
this.OnPdfFileCreationCompleted(data2);
return true;
}
flag = false;
}
catch (Exception exception)
{
flag = false;
StringBuilder builder2 = new StringBuilder();
builder2.Append(builder.ToString());
builder2.Append(": \t");
builder2.Append(exception.Message);
this.m_excepLogger.LogException(builder2.ToString());
}
return flag;
}
The OP creates the iTextSharp Image object like this:
Bitmap bitmap = new Bitmap(data.FilePath);
iTextSharp.text.Image instance = iTextSharp.text.Image.GetInstance(bitmap, ImageFormat.Png);
What this actually means is that the original image file is decoded into a bitmap, and then iTextSharp is asked to use the bitmap as if it was a PNG image.
In case of JPG images this usually means that the amount of data required to store the image explodes.
To prevent such size explosions one should allow iTextSharp to directly work with the original image file data, in the context at hand:
iTextSharp.text.Image instance = iTextSharp.text.Image.GetInstance(data.FilePath);

how to save image on android in unity

I'm new in Unity and I'm trying to save an image for get it after. I try Application.CaptureScreenshot and the method with Texture2D.ReadPixel, i try to save in persistentDataPath (/data/user/0/my.package.name/files/), in /sdcard/Download/ and in /storage/emulated/0/Download. No method worked. In every manifest of my project I have WRITE_EXTERNAL_STORAGE permission. If I save to persistent data, I don't found it I found only cache of UnityAds, and if I save to Download folder I get access denied.
Anyone can help me?
Here's my code :
IEnumerator ScreenShot(){
yield return new WaitForEndOfFrame ();
Application.CaptureScreenshot ("ball.png");
Application.CaptureScreenshot ("/sdcard/Download/ball.png");
int width = Screen.width;
int height = Screen.height;
Texture2D tex = new Texture2D (width, height, TextureFormat.RGB24, false);
tex.ReadPixels (new Rect (0, 0, width, height), 0, 0);
tex.Apply ();
byte[] bytes = tex.EncodeToJPG ();
File.WriteAllBytes ("sdcard/Download/ball.png", bytes);
File.WriteAllBytes (Application.persistentDataPath + "/ball.png", bytes);
}
Before i check if folders exist :
if(!System.IO.Directory.Exists("/sdcard/Download/"))
{
System.IO.Directory.CreateDirectory ("/sdcard/Download/");
}
if(!System.IO.Directory.Exists(Application.persistentDataPath))
{
System.IO.Directory.CreateDirectory (Application.persistentDataPath);
}
And I start IEnumerator with:
StartCoroutine(ScreenShot());
What I'm doing wrong?
Here is what works for me:
string destination = DateTime.Now.ToString ("yyyy-MM-dd-HHmmss") + ".png";
string fullDestination = Path.Combine (Application.persistentDataPath, destination);
Application.CaptureScreenshot (destination);
SharingWriter.WriteTextInstant ("Preparing...");
FileInfo fileInfo = new FileInfo(fullDestination);
while(fileInfo == null || fileInfo.Exists == false)
{
yield return null;
fileInfo = new FileInfo(fullDestination);
}
Application.CaptureScreenshot handles everything, no need to worry about reading pixels and writing to files that's redundant. Just have a while loop afterwards in the Coroutine to wait for the magic to happen! I used this to create screenshot sharing functionality for mobile.

NGif Animator Background Problems

I've been playing around with NGif Animator for resizing animated gifs and it does resize but parts in many animated gifs I've tried get erased. I looked through the comments on that page and didn't see anyone else mention it.
To eliminate resizing as the cause I simply loop through the frames and save each one. Each frame is a System.Drawing.Image. Transparency is set to none (Color.Empty).
This is my test method currently:
GifDecoder gifDecoder = new GifDecoder();
MemoryStream memoryStream = new MemoryStream();
new BinaryWriter((Stream)memoryStream).Write(imageToResize); // byte array
memoryStream.Position = 0L;
gifDecoder.Read((Stream)memoryStream);
memoryStream.Dispose();
string filename = Guid.NewGuid().ToString().Replace("-", String.Empty) + ".gif";
string output = path + #"\" + filename;
AnimatedGifEncoder animatedGifEncoder = new AnimatedGifEncoder();
animatedGifEncoder.Start(output);
animatedGifEncoder.SetRepeat(gifDecoder.GetLoopCount());
animatedGifEncoder.SetQuality(10); // They say 20 is max quality will get, I've tried higher. Makes it a little bit better but black areas instead of gray. 10 is their default.
animatedGifEncoder.SetTransparent(Color.Empty); // This is default either way
int frameCount = gifDecoder.GetFrameCount();
int num = 0;
Image frame;
Image image = null;
for (int index = frameCount; num < index; ++num)
{
frame = gifDecoder.GetFrame(num);
animatedGifEncoder.SetDelay(gifDecoder.GetDelay(num));
string fname = #"C:\Development\images\frame_" + num.ToString() + ".gif";
if (File.Exists(fname)) { File.Delete(fname); }
frame.Save(fname);
animatedGifEncoder.AddFrame(image);
}
animatedGifEncoder.Finish();
Here's an example of what's happening:
The background is gone and it's gray.
It's supposed to look like:
Anyone have experience with NGif and know what would cause this? The first frame is always fine. It's the others after that have a problem so I'm guessing something isn't being reset from frame to frame (or re-read). I've been adding more things to their reset frame method but so far it hasn't helped. That now looks like:
protected void ResetFrame()
{
lastDispose = dispose;
lastRect = new Rectangle(ix, iy, iw, ih);
lastImage = image;
lastBgColor = bgColor;
delay = 0;
transparency = false; // I don't want transparency
lct = null;
act = null;
transIndex = -1;
}
There is actually a bug in their code, a byte array not being reset. Check the comments on their page for a solution

Categories

Resources