public static Result DecodeImage(Texture2D tex) { Color32LuminanceSource colLumSource = new Color32LuminanceSource(tex.GetPixels32(), tex.width, tex.height); HybridBinarizer hybridBinarizer = new HybridBinarizer(colLumSource); BinaryBitmap bitMap = new BinaryBitmap(hybridBinarizer); //We reset before we decode for safety; CodeReader.reset(); return CodeReader.decode(bitMap); }
/// <summary> /// Receives the original texture so it doesn't have to instantiate it every time. /// </summary> /// <param name="original"></param> public Rotation(Texture2D original, Vector2 pivot, int pixelsPerUnit) { _newTexture = (Texture2D)MonoBehaviour.Instantiate(original); _oldArray = original.GetPixels32(); _newArray = new Color32[original.GetPixels32().Length]; _width = original.width; _height = original.height; _pivot = pivot; _pixelsPerUnit = pixelsPerUnit; }
void Start() { Texture2D mip = new Texture2D(tileTex.width, tileTex.height, TextureFormat.ARGB32, true, false); { tileTex.filterMode = FilterMode.Point; var pdata = tileTex.GetPixels32(0); mip.SetPixels32(pdata, 0); mip.Apply(true); } int width = tileTex.width; int layer = 0; while (width > tileSplit) { width /= 2; layer++; Debug.Log("p layer:" + layer); Texture2D m = new Texture2D(width, width, TextureFormat.ARGB32, false, true); m.filterMode = FilterMode.Point; var d = mip.GetPixels32(layer); m.SetPixels32(d, 0); m.Apply(); mipTileTex.Add(m); } GameObject.Destroy(mip); wordData = new worldData[srcTex.width * srcTex.height]; scale = srcTex.width; }
static int GetPixels32(IntPtr L) { try { int count = LuaDLL.lua_gettop(L); if (count == 1) { UnityEngine.Texture2D obj = (UnityEngine.Texture2D)ToLua.CheckObject(L, 1, typeof(UnityEngine.Texture2D)); UnityEngine.Color32[] o = obj.GetPixels32(); ToLua.Push(L, o); return(1); } else if (count == 2) { UnityEngine.Texture2D obj = (UnityEngine.Texture2D)ToLua.CheckObject(L, 1, typeof(UnityEngine.Texture2D)); int arg0 = (int)LuaDLL.luaL_checknumber(L, 2); UnityEngine.Color32[] o = obj.GetPixels32(arg0); ToLua.Push(L, o); return(1); } else { return(LuaDLL.luaL_throw(L, "invalid arguments to method: UnityEngine.Texture2D.GetPixels32")); } } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
// ------------------------------------------------------------------ /// \param _tex the texture in which to apply contour bleed /// prevents edge artifacts due to bilinear filtering /// Note: Some image editors like Photoshop tend to fill purely transparent pixel with /// white color (R=1, G=1, B=1, A=0). This is generally OK, because these white pixels /// are impossible to see in normal circumstances. However, when such textures are /// used in 3D with bilinear filtering, the shader will sometimes sample beyond visible /// edges into purely transparent pixels and the white color stored there will bleed /// into the visible edge. This method scans the texture to find all purely transparent /// pixels that have a visible neighbor pixel, and copy the color data from that neighbor /// into the transparent pixel, while preserving its 0 alpha value. In order to /// optimize the algorithm for speed of execution, a compromise is made to use any /// arbitrary neighboring pixel, as this should generally lead to correct results. /// It also limits itself to the immediate neighbors around the edge, resulting in a /// a bleed of a single pixel border around the edges, which should be fine, as bilinear /// filtering should generally not sample beyond that one pixel range. // ------------------------------------------------------------------ public static Texture2D ApplyContourBleed( Texture2D _tex ) { // Extract pixel buffer to be modified Color32[] pixels = _tex.GetPixels32(0); for ( int x = 0; x < _tex.width; ++x ) { for ( int y = 0; y < _tex.height; ++y ) { // only try to bleed into purely transparent pixels if ( pixels[x + y * _tex.width].a == 0 ) { // sample all around to find any non-purely transparent pixels for ( int i = 0; i < bleedXOffsets.Length; i++ ) { int sampleX = x + bleedXOffsets[i]; int sampleY = y + bleedYOffsets[i]; // check to stay within texture bounds if (sampleX >= 0 && sampleX < _tex.width && sampleY >= 0 && sampleY < _tex.height) { Color32 color = pixels[sampleX + sampleY * _tex.width]; if (color.a != 0) { // Copy RGB color channels to purely transparent pixel, but preserving its 0 alpha pixels[x + y * _tex.width] = new Color32(color.r, color.g, color.b, 0); break; } } } } } } // Copy modified pixel buffer to new texture (to preserve original element texture and allow user to uncheck the option) Texture2D tex = new Texture2D(_tex.width, _tex.height, _tex.format, false); tex.SetPixels32(pixels); return tex; }
/// <summary> /// Adds a frame to the animated GIF. If this is the first frame, it will be used to specify the size and color palette of the GIF. /// </summary> public void AddFrame(Texture2D frame) { if (!this.sizeSet) { // use first frame's size this.width = frame.width; this.height = frame.height; this.sizeSet = true; } this.currentFramePixels = frame.GetPixels32(); this.GetImagePixels(); // convert to correct format if necessary this.AnalyzePixels(); // build color table & map pixels if (this.firstFrame) { this.WriteLSD(); // logical screen descriptior this.WritePalette(); // global color table if (this.repeat >= 0) { // use NS app extension to indicate reps this.WriteNetscapeExt(); } } this.WriteGraphicCtrlExt(); // write graphic control extension this.WriteImageDesc(); // image descriptor this.WritePixels(); // encode and write pixel data this.firstFrame = false; }
static public int GetPixels32(IntPtr l) { try{ int argc = LuaDLL.lua_gettop(l); if (argc == 2) { UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l); System.Int32 a1; checkType(l, 2, out a1); UnityEngine.Color32[] ret = self.GetPixels32(a1); pushValue(l, ret); return(1); } else if (argc == 1) { UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l); UnityEngine.Color32[] ret = self.GetPixels32(); pushValue(l, ret); return(1); } LuaDLL.luaL_error(l, "No matched override function to call"); return(0); } catch (Exception e) { LuaDLL.luaL_error(l, e.ToString()); return(0); } }
static public int GetPixels32(IntPtr l) { try { int argc = LuaDLL.lua_gettop(l); if (argc == 2) { UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l); System.Int32 a1; checkType(l, 2, out a1); var ret = self.GetPixels32(a1); pushValue(l, true); pushValue(l, ret); return(2); } else if (argc == 1) { UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l); var ret = self.GetPixels32(); pushValue(l, true); pushValue(l, ret); return(2); } pushValue(l, false); LuaDLL.lua_pushstring(l, "No matched override function to call"); return(2); } catch (Exception e) { return(error(l, e)); } }
// Texture Function -------------------------------------------------------------- public static Texture2D CopyTexture(Texture2D srcTex, Texture2D tarTex) { Color32[] colBuf = srcTex.GetPixels32(); tarTex.SetPixels32(colBuf); tarTex.Apply(false); return tarTex; }
// Distinguish completely transparent pixels from significant pixel by // "binarizing" the texture via a bit array. // false if a pixel is not significant (= transparent), true otherwise public static BinarizedImage BinarizeTexture( Texture2D a_rTextureToFilter, float a_fAlphaCutOff ) { if(a_rTextureToFilter == null) { return null; } float fAlphaCutOff32 = a_fAlphaCutOff * 255; // Retrieve texture pixels (in 32bits format) // Array is flattened / pixels laid left to right, bottom to top Color32[ ] oTexturePixels = a_rTextureToFilter.GetPixels32( ); int iPixelCount = oTexturePixels.Length; // Create (padded) sprite shape pixels array (bit array) BinarizedImage oBinarizedTexture = new BinarizedImage( a_rTextureToFilter.width, a_rTextureToFilter.height, false ); // Parse all pixels for( int iPixelIndex = 0; iPixelIndex < iPixelCount; ++iPixelIndex ) { Color32 f4Pixel = oTexturePixels[ iPixelIndex ]; oBinarizedTexture.SetUnpaddedPixel( iPixelIndex, ( f4Pixel.a >= fAlphaCutOff32 ) ); } // Fill 1px holes oBinarizedTexture.FillInsulatedHoles( ); return oBinarizedTexture; }
//========================================================================= // Methods created by petrucio -> http://answers.unity3d.com/questions/238922/png-transparency-has-white-borderhalo.html // // Copy the values of adjacent pixels to transparent pixels color info, to // remove the white border artifact when importing transparent .PNGs. public static void FixTransparency(Texture2D texture) { Color32[] pixels = texture.GetPixels32(); int w = texture.width; int h = texture.height; for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { int idx = y * w + x; Color32 pixel = pixels[idx]; if (pixel.a == 0) { bool done = false; if (!done && x > 0) done = TryAdjacent(ref pixel, pixels[idx - 1]); // Left pixel if (!done && x < w - 1) done = TryAdjacent(ref pixel, pixels[idx + 1]); // Right pixel if (!done && y > 0) done = TryAdjacent(ref pixel, pixels[idx - w]); // Top pixel if (!done && y < h - 1) done = TryAdjacent(ref pixel, pixels[idx + w]); // Bottom pixel pixels[idx] = pixel; } } } texture.SetPixels32(pixels); texture.Apply(); }
// public Texture2D DoDithering(Texture2D input) { this.width = input.width; this.height = input.height; // Copy all pixels of input Texture2D to new array, which we are going to edit this.pixels = input.GetPixels32(); Color32 originalPixel = Color.white; // Default value isn't used Color32 newPixel = Color.white; // Default value isn't used short[] quantError = null; // Default values aren't used for (int y = 0; y < this.height; y++) { for (int x = 0; x < this.width; x++) { originalPixel = this.pixels[GetIndexWith(x, y)]; newPixel = this.colorFunction(originalPixel); this.pixels[GetIndexWith(x, y)] = newPixel; quantError = GetQuantError(originalPixel, newPixel); this.PushError(x, y, quantError); } } // Create the texture we are going to return from pixels array Texture2D returnTexture = new Texture2D(width, height, TextureFormat.ARGB32, false); returnTexture.SetPixels32(this.pixels); returnTexture.Apply(); return returnTexture; }
void Update() { if (state == 0) { AndroidJavaClass UnityOpenCVLoaderJava = new AndroidJavaClass(UNITY_OPENCV_LOADER); var b = UnityOpenCVLoaderJava.CallStatic<Boolean>("isSuccess"); if (b) { state = 1; } } else if (state == 1) { if (cameraInstance == IntPtr.Zero) cameraInstance = CreateCameraInstance (); if (Open (cameraInstance, 0, width, height)) { texture = new Texture2D (width, height, TextureFormat.ARGB32, false); pixels = texture.GetPixels32 (); pixelsHandle = GCHandle.Alloc (pixels, GCHandleType.Pinned); pixelsPtr = pixelsHandle.AddrOfPinnedObject (); GetComponent<Renderer>().material.mainTexture = texture; state = 2; } else { state = -1; } } else if (state == 2) { getCameraTexture (cameraInstance, pixelsPtr, width, height); texture.SetPixels32 (pixels); texture.Apply (); } }
void LoadTexDistanceField(string name) { #if UNITY_STANDALONE string filename = System.IO.Path.Combine(Application.streamingAssetsPath, name + ".png"); string filename_df = System.IO.Path.Combine(Application.streamingAssetsPath, name + "_df.png"); //if (System.IO.File.Exists(filename_df)) //{ // Texture2D tex = new Texture2D(1, 1); // tex.LoadImage(System.IO.File.ReadAllBytes(filename_df)); // texs[name] = tex; //} //else { Texture2D tex = new Texture2D(1, 1); tex.LoadImage(System.IO.File.ReadAllBytes(filename));//加载原始图片 Color32[] _bsdata = tex.GetPixels32(0); KDTree2D tree = new KDTree2D(); List<KDTree2D.Train> treedata = new List<KDTree2D.Train>(); FindBorder(tex.width,tex.height,_bsdata, treedata);//四次采样寻找边界,并把在边界上的点填入点集 var node = tree.CreatKDTree(treedata);//用KDTree来查找最近点 int w = tex.width; int h = tex.height; DateTime t1 = DateTime.Now; float maxlen = (float)Mathf.Sqrt(w * w + h * h) / 4; for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { var near = tree.KDTreeFindNearest(node, new KDTree2D.Train() { positionX = x, positionY = y }); float d = (float)Mathf.Sqrt((near.point.positionX - x) * (near.point.positionX - x) + (near.point.positionY - y) * (near.point.positionY - y)); if (_bsdata[y * w + x].a < 128) { d *= -1; _bsdata[y * w + x]= _bsdata[(int)near.point.positionY * w + (int)near.point.positionX]; } float dist = d / maxlen; if (dist < -1) dist = -1; if (dist > 1) dist = 1; var b = (byte)(128 + 127.0f * dist); _bsdata[y * w + x].a = b;//替换原alpha值为距离值,形状内>128,形状外<128 } } DateTime t2 = DateTime.Now; Debug.Log("t=" + (t2 - t1).TotalSeconds); tex.SetPixels32(_bsdata); tex.Apply(); System.IO.File.WriteAllBytes(filename_df, tex.EncodeToPNG());//保存为新文件 texs[name] = tex; } #endif }
public static void GetDXT(Texture2D texture, int i, byte[] bytes, TextureFormat format) { Color32[] colors = texture.GetPixels32(i); uint w = (uint) texture.width>>i; uint h = (uint) texture.height>>i; ColorBlock rgba = new ColorBlock(); BlockDXT1 block1 = new BlockDXT1(); BlockDXT5 block5 = new BlockDXT5(); int blocksize = format == TextureFormat.DXT1 ? 8 : 16; int index = 0; for (uint y = 0; y < h; y += 4) { for (uint x = 0; x < w; x += 4) { rgba.init(w, h, colors, x, y); if (format == TextureFormat.DXT1) { QuickCompress.compressDXT1(rgba, block1); block1.WriteBytes(bytes, index); } else { QuickCompress.compressDXT5(rgba, block5, 0); block5.WriteBytes(bytes, index); } index += blocksize; } } }
public void UpdateByTexture2D(Texture2D i_wtx) { System.Diagnostics.Debug.Assert(this._size.isEqualSize(i_wtx.width, i_wtx.height)); this._buf = i_wtx.GetPixels32(); this._rgb_pixel_driver.switchRaster(this); return; }
static int QPYX_GetPixels32_YXQP(IntPtr L_YXQP) { try { int QPYX_count_YXQP = LuaDLL.lua_gettop(L_YXQP); if (QPYX_count_YXQP == 1) { UnityEngine.Texture2D QPYX_obj_YXQP = (UnityEngine.Texture2D)ToLua.CheckObject(L_YXQP, 1, typeof(UnityEngine.Texture2D)); UnityEngine.Color32[] QPYX_o_YXQP = QPYX_obj_YXQP.GetPixels32(); ToLua.Push(L_YXQP, QPYX_o_YXQP); return(1); } else if (QPYX_count_YXQP == 2) { UnityEngine.Texture2D QPYX_obj_YXQP = (UnityEngine.Texture2D)ToLua.CheckObject(L_YXQP, 1, typeof(UnityEngine.Texture2D)); int QPYX_arg0_YXQP = (int)LuaDLL.luaL_checknumber(L_YXQP, 2); UnityEngine.Color32[] QPYX_o_YXQP = QPYX_obj_YXQP.GetPixels32(QPYX_arg0_YXQP); ToLua.Push(L_YXQP, QPYX_o_YXQP); return(1); } else { return(LuaDLL.luaL_throw(L_YXQP, "invalid arguments to method: UnityEngine.Texture2D.GetPixels32")); } } catch (Exception e_YXQP) { return(LuaDLL.toluaL_exception(L_YXQP, e_YXQP)); } }
void OnGUI() { if (finalize) { // select created texture Selection.activeObject=AssetDatabase.LoadAssetAtPath(save_path, typeof(Texture2D)); finalize=false; } EditorGUILayout.Space(); source_tex0 = EditorGUILayout.ObjectField("Source Texture 0", source_tex0, typeof(Texture2D), false) as Texture2D; EditorGUILayout.Space(); source_tex1 = EditorGUILayout.ObjectField("Source Texture 1", source_tex1, typeof(Texture2D), false) as Texture2D; EditorGUILayout.Space(); source_tex2 = EditorGUILayout.ObjectField("Source Texture 2", source_tex2, typeof(Texture2D), false) as Texture2D; EditorGUILayout.Space(); source_tex3 = EditorGUILayout.ObjectField("Source Texture 3", source_tex3, typeof(Texture2D), false) as Texture2D; EditorGUILayout.Space(); if (source_tex0) { int sources_ready=0; if (check_texture(source_tex0, 0, source_tex0.width, source_tex0.height)) { sources_ready++; sourceChannel0 = (RTPColorChannels)EditorGUILayout.EnumPopup("Target R from source 0", sourceChannel0); } if (check_texture(source_tex1, 1, source_tex0.width, source_tex0.height)) { sources_ready++; sourceChannel1 = (RTPColorChannels)EditorGUILayout.EnumPopup("Target G from source 1", sourceChannel1); } if (check_texture(source_tex2, 2, source_tex0.width, source_tex0.height)) { sources_ready++; sourceChannel2 = (RTPColorChannels)EditorGUILayout.EnumPopup("Target B from source 2", sourceChannel2); } if (check_texture(source_tex3, 3, source_tex0.width, source_tex0.height)) { sources_ready++; sourceChannel3 = (RTPColorChannels)EditorGUILayout.EnumPopup("Target A from source 3", sourceChannel3); } if (sources_ready==4) { if (GUILayout.Button("Render mixed texture")) { rendered_tex=new Texture2D(source_tex0.width, source_tex0.height, TextureFormat.ARGB32, true); byte[] colsR=get_color_channel(source_tex0, sourceChannel0); byte[] colsG=get_color_channel(source_tex1, sourceChannel1); byte[] colsB=get_color_channel(source_tex2, sourceChannel2); byte[] colsA=get_color_channel(source_tex3, sourceChannel3); Color32[] cols=rendered_tex.GetPixels32(); for(int i=0; i<cols.Length; i++) { cols[i].r=colsR[i]; cols[i].g=colsG[i]; cols[i].b=colsB[i]; cols[i].a=colsA[i]; } rendered_tex.SetPixels32(cols); if (Selection.activeObject is Texture2D) { save_path=AssetDatabase.GetAssetPath(Selection.activeObject as Texture2D); directory=Path.GetDirectoryName(save_path); file=Path.GetFileNameWithoutExtension(save_path)+".png"; } else { if (save_path=="") { directory=Path.GetDirectoryName(AssetDatabase.GetAssetPath(source_tex0)); file=Path.GetFileNameWithoutExtension(AssetDatabase.GetAssetPath(source_tex0))+"(mixed).png"; } } } } } if (rendered_tex) { linearTexture=GUILayout.Toggle(linearTexture, "Linear texture (Bypass sRGB Sampling)"); if (GUILayout.Button("Save texture")) { SaveTexture(directory, file); } } }
public static void FlipTexture2DVertically(Texture2D texture2D) { var pixels = texture2D.GetPixels32(); Utils.Flip2DArrayVertically(pixels, texture2D.height, texture2D.width); texture2D.SetPixels32(pixels); texture2D.Apply(); }
void Start() { //controller should be set by the controller _texture = GetComponent<SpriteRenderer>().sprite.texture; _pixels = _texture.GetPixels32(); //TODO Optimize: precache indices and local positions of pixels with a>0 }
// Use this for initialization void Start () { camera_ = getCamera(device); setCameraProp(camera_, width, height, fps); texture_ = new Texture2D(width, height, TextureFormat.ARGB32, false); pixels_ = texture_.GetPixels32(); pixels_handle_ = GCHandle.Alloc(pixels_, GCHandleType.Pinned); pixels_ptr_ = pixels_handle_.AddrOfPinnedObject(); GetComponent<Renderer>().material.mainTexture = texture_; }
IEnumerator Start() { if (signal == null) signal = Enumerable.Repeat(originalSignal, 3).SelectMany(b => b).ToArray(); tex = new Texture2D(1024, 512, TextureFormat.ARGB32, false); rend.material.mainTexture = tex; Color32[] cols = tex.GetPixels32(); //byte[] send = new byte[cols.Length * 4]; Write("230.0.0.1", 9876); int dataSize = sendAlpha ? 4 : 3; while(true) { yield return null; if (Input.GetKeyDown(KeyCode.H)) { Debug.Log("Sent so far: " + sent); } if (Input.GetKeyDown(KeyCode.G)) { for(int i = 0; i < cols.Length; ++i) { cols[i]= new Color32((byte)Random.Range(0,255), (byte)Random.Range(0,255), (byte)Random.Range(0,255), (byte)255); } tex.SetPixels32(cols); tex.Apply(); /* for(int i = 0; i < cols.Length; ++i) { for(int j = 0; j < dataSize; ++j) { var col = cols[i]; switch(j) { case 0: default: send[i*dataSize + j] = col.r; break; case 1: send[i*dataSize + j] = col.g; break; case 2: send[i*dataSize + j] = col.b; break; case 3: send[i*dataSize + j] = col.a; break; } } } */ AddData(tex.EncodeToPNG()); //AddData(send); } } }
/// <summary> /// Imports a generic pixel font from texture. /// Source atlas texture: /// * Must be readable /// * Must start from ASCII 0 character /// * Must not have more than 256 characters total /// * Must increment characters left to right, top to bottom (with 0 at top-left) /// </summary> /// <param name="texture">Source texture atlas.</param> /// <param name="glyphsWide">Number of glyphs packed horizontally.</param> /// <param name="glyphsHigh">Number of glyphs packed vertically.</param> /// <param name="dimension">Dimension of each glyph.</param> /// <param name="proportional">Discover proportional width of glyphs.</param> public void ImportBitmapFont(Texture2D texture, int glyphsWide, int glyphsHigh, int dimension, bool proportional = true) { // Validate count int count = glyphsWide * glyphsHigh; if (count > 256) { throw new Exception("ImportBitmapFont: Glyph count > 256."); } // Validate dimensions if (glyphsWide * dimension > texture.width || glyphsHigh * dimension > texture.height) { throw new Exception("ImportBitmapFont: Invalid texture dimensions."); } // Get texture as Color32 array Color32[] colors = texture.GetPixels32(); // Start new glyph dictionary ClearGlyphs(); // Store settings atlasTexture = texture; GlyphHeight = dimension; asciiStart = 0; // Generate rects if (!proportional) atlasRects = GenerateNonProportionalRects(texture.width, texture.height, glyphsWide, glyphsHigh, dimension, count); else atlasRects = GenerateProportionalRects(ref colors, texture.width, texture.height, glyphsWide, glyphsHigh, dimension, count); // Add glyphs //int xpos = 0; //int ypos = 0; //DFSize srcSize = new DFSize(texture.width, texture.height); //DFSize dstSize = new DFSize(dimension, dimension); for (int i = 0; i < count; i++) { //Color32[] dst = new Color32[dimension * dimension]; //ImageProcessing.CopyColors(ref colors, ref dst, srcSize, dstSize, new DFPosition(xpos, ypos), new DFPosition(0, 0), dstSize); GlyphInfo glyph = new GlyphInfo(); //glyph.colors = dst; glyph.width = (int)(atlasRects[i].width * texture.width); AddGlyph(i, glyph); //xpos += dimension; //if (xpos > texture.width) //{ // xpos = 0; // ypos += dimension; //} } }
public void OnEnable() { m_texture = new Texture2D(TextureSize, TextureSize, TextureFormat.ARGB32, false); m_texture.filterMode = FilterMode.Point; m_pixels = m_texture.GetPixels32(); if (PlotMaterial) { PlotMaterial.mainTexture = m_texture; } }
/// Call this to capture a custom, screenshot public static Texture2D CaptureCustomScreenshot(int width, int height) { UnityEngine.Texture2D textured = new UnityEngine.Texture2D(width, height, UnityEngine.TextureFormat.RGB24, true, false); textured.ReadPixels(new UnityEngine.Rect(0f, 0f, (float)width, (float)height), 0, 0); int miplevel = UnityEngine.Screen.width / 800; UnityEngine.Texture2D textured2 = new UnityEngine.Texture2D(width >> miplevel, height >> miplevel, UnityEngine.TextureFormat.RGB24, false, false); textured2.SetPixels32(textured.GetPixels32(miplevel)); textured2.Apply(); return textured2; }
public static Texture2D createTexture(int width, int height, Color color){ Texture2D tex = new Texture2D(width,height,TextureFormat.ARGB32,false); Color32[] pixels=tex.GetPixels32(); for (int i=0;i<pixels.Length;i++){ pixels[i]=color; } tex.SetPixels32(pixels); tex.Apply(false); return tex; }
byte[] get_color_channel(Texture2D source_tex, RTPColorChannels sourceChannel) { Color32[] cols=source_tex.GetPixels32(); byte[] ret=new byte[cols.Length]; if (sourceChannel==RTPColorChannels.R) for(int i=0; i<cols.Length; i++) ret[i]=cols[i].r; if (sourceChannel==RTPColorChannels.G) for(int i=0; i<cols.Length; i++) ret[i]=cols[i].g; if (sourceChannel==RTPColorChannels.B) for(int i=0; i<cols.Length; i++) ret[i]=cols[i].b; if (sourceChannel==RTPColorChannels.A) for(int i=0; i<cols.Length; i++) ret[i]=cols[i].a; return ret; }
public static Texture2D InverseTexture32(Texture2D srcTex, Texture2D tarTex) { Color32[] colBuf = srcTex.GetPixels32(); for (int n = 0; n < colBuf.Length; n++) colBuf[n].a = (byte)(255 - colBuf[n].a); tarTex.SetPixels32(colBuf); tarTex.Apply(false); return tarTex; }
/// <summary> /// Call this to capture a custom, screenshot /// </summary> /// <param name="width"></param> /// <param name="height"></param> /// <returns></returns> public static Texture2D CaptureCustomScreenshot(int width, int height) { UnityEngine.Texture2D textured = new UnityEngine.Texture2D(width, height, UnityEngine.TextureFormat.RGB24, true, false); textured.ReadPixels(new UnityEngine.Rect(0f, 0f, (float)width, (float)height), 0, 0); int miplevel = UnityEngine.Screen.width / 800; UnityEngine.Texture2D textured2 = new UnityEngine.Texture2D(width >> miplevel, height >> miplevel, UnityEngine.TextureFormat.RGB24, false, false); textured2.SetPixels32(textured.GetPixels32(miplevel)); textured2.Apply(); return(textured2); }
public static Vector4 ComputePadding(Texture2D texture, Rect rect) { var colors = texture.GetPixels32(); float left = 0, right = 0, top = 0, bottom = 0; int stride = texture.width; int xMin = (int) rect.xMin; int yMin = (int) rect.yMin; int xMax = (int) (rect.xMax - 1); // xMax and yMax of rect is working a little different than expected int yMax = (int) (rect.yMax - 1); // scanning left for (int i = xMin; i < xMax; ++i) { if (HasVisibleVert(i, colors, rect, stride)) { left = i; break; } } // scanning right for (int i = xMin; i < xMax; ++i) { int i2 = xMax - i - 1; if (HasVisibleVert(i2, colors, rect, stride)) { right = i; break; } } // scanning bottom for (int i = yMin; i < yMax; ++i) { if (HasVisibleHoriz(i, colors, rect, stride)) { bottom = i; break; } } // scanning top for (int i = yMin; i < yMax; i++) { int i2 = yMax - i - 1; if (HasVisibleHoriz(i2, colors, rect, stride)) { top = i; break; } } // apply 2 pixel padding left = Mathf.Max(0, left - 2); bottom = Mathf.Max(0, bottom - 2); right = Mathf.Max(0, right - 2); top = Mathf.Max(0, top - 2); return new Vector4(left, bottom, right, top); }
public static Texture2D generateBlankNormal () { Texture2D texture = new Texture2D ( 16, 16, TextureFormat.ARGB32, false ); Color32[] cols = texture.GetPixels32 ( 0 ); int colsLength = cols.Length; for( int i=0 ; i < colsLength; i++ ) { cols[i] = new Color ( 0f, 0.5f, 0f, 0.5f ); } texture.SetPixels32 ( cols, 0 ); texture.Apply(); texture.Compress ( false ); return texture; }
public D2D_Pixels(Texture2D texture) { if (texture == null) throw new System.ArgumentNullException(); #if UNITY_EDITOR D2D_Helper.MakeTextureReadable(texture); #endif width = texture.width; height = texture.height; pixels = texture.GetPixels32(); }
//////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// /// <summary> /// Re sample and crop a texture /// </summary> /// <param name="p_Source">Source texture</param> /// <param name="p_TargetWidth">Target width</param> /// <param name="p_TargetHeight">Target height</param> /// <returns></returns> public static UnityEngine.Texture2D ResampleAndCrop(UnityEngine.Texture2D p_Source, int p_TargetWidth, int p_TargetHeight, float p_YOffsetRel = 0.5f) { int l_SourceWidth = p_Source.width; int l_SourceHeight = p_Source.height; float l_SourceAspect = (float)l_SourceWidth / l_SourceHeight; float l_TargetAspect = (float)p_TargetWidth / p_TargetHeight; int l_XOffset = 0; int l_YOffset = 0; float l_Factor; /// Crop width if (l_SourceAspect > l_TargetAspect) { l_Factor = (float)p_TargetHeight / l_SourceHeight; l_XOffset = (int)((l_SourceWidth - l_SourceHeight * l_TargetAspect) * 0.5f); } /// Crop height else { l_Factor = (float)p_TargetWidth / l_SourceWidth; l_YOffset = (int)((l_SourceHeight - l_SourceWidth / l_TargetAspect) * (1f - p_YOffsetRel)); } Color32[] l_Source = p_Source.GetPixels32(); Color32[] l_Result = new Color32[p_TargetWidth * p_TargetHeight]; for (int l_Y = 0; l_Y < p_TargetHeight; l_Y++) { for (int l_X = 0; l_X < p_TargetWidth; l_X++) { var l_Pixel = new Vector2(Mathf.Clamp(l_XOffset + l_X / l_Factor, 0, l_SourceWidth - 1), Mathf.Clamp(l_YOffset + l_Y / l_Factor, 0, l_SourceHeight - 1)); /// Bilinear filtering var l_C11 = l_Source[Mathf.FloorToInt(l_Pixel.x) + l_SourceWidth * (Mathf.FloorToInt(l_Pixel.y))]; var l_C12 = l_Source[Mathf.FloorToInt(l_Pixel.x) + l_SourceWidth * (Mathf.CeilToInt(l_Pixel.y))]; var l_C21 = l_Source[Mathf.CeilToInt(l_Pixel.x) + l_SourceWidth * (Mathf.FloorToInt(l_Pixel.y))]; var l_C22 = l_Source[Mathf.CeilToInt(l_Pixel.x) + l_SourceWidth * (Mathf.CeilToInt(l_Pixel.y))]; l_Result[l_X + l_Y * p_TargetWidth] = Color.Lerp(Color.Lerp(l_C11, l_C12, l_Pixel.y), Color.Lerp(l_C21, l_C22, l_Pixel.y), l_Pixel.x); } } var l_ResultTexture = new UnityEngine.Texture2D(p_TargetWidth, p_TargetHeight); l_ResultTexture.SetPixels32(l_Result); l_ResultTexture.Apply(true); return(l_ResultTexture); }
IEnumerator ReqRecogImg(Texture2D sourceTex) { // NTTサイトで取得したAPIKEYを指定 string apikey="547047744738754a4a553175766354513855635349304c7650574a6a32486e69632f4c49464a306d7a5a43"; // NTTの画像認識サーバーへのリクエストURL string url="https://api.apigw.smt.docomo.ne.jp/imageRecognition/v1/recognize?APIKEY="+apikey+"&recog=product-all&numOfCandidates=2"; //テクスチャをJPG形式のバイナリに変換して、リクエストのボディーに設定 Texture2D tex2d2 = new Texture2D (sourceTex.width, sourceTex.height); tex2d2.SetPixels32 (sourceTex.GetPixels32 ()); tex2d2.Apply (); byte[] bytes = tex2d2.EncodeToJPG (); Dictionary<string,string> has = new Dictionary<string,string>(); has.Add("Content-Type", "application/octet-stream"); // HTTPリクエスト開始 WWW www = new WWW(url,bytes,has); // サーバーにリクエストを行いレスポンスを待つ yield return www; Debug.Log(www.text); // サーバーから取得したレスポンスのテキストをJSONパーサー(MiniJson)でパースする var json = Json.Deserialize (www.text) as Dictionary<string, object>; recogName = "unknown"; if (!json.ContainsKey ("candidates")) { recogBFlag = false; yield break; } IList candi = json ["candidates"] as IList; if (candi != null) { foreach (var obj in candi) { var c = obj as IDictionary; if(c==null || !c.Contains("detail")){ continue; } IDictionary detail=(IDictionary)c["detail"]; if(detail!=null){ string itemName=(string)detail["itemName"]; if(itemName!=null){ Debug.Log (itemName); recogName=itemName; break; } } } } recogBFlag = false; }
public ChannelTexture(int width, int height, TextureFormat format) { tex = new Texture2D(width, height, format, false); tex.wrapMode = TextureWrapMode.Clamp; //important for NPOT #if !((UNITY_ANDROID || UNITY_IPHONE) && !UNITY_EDITOR) pixels = tex.GetPixels32(0); handle = GCHandle.Alloc(pixels, GCHandleType.Pinned); #endif ReAlloc(); }
public PSEyeTexture(int camera_number, int frame_rate, bool is_reverse = false) { // set member CameraNumber = camera_number; FrameRate = frame_rate; // create CLEye Camera camera_ = CLEyeCreateCamera(CameraUUID(CameraNumber), CLEyeCameraColorMode.CLEYE_COLOR_RAW, CLEyeCameraResolution.CLEYE_VGA, FrameRate); CLEyeCameraGetFrameDimensions(camera_, ref width_, ref height_); // set auto mode AutoGain = true; AutoWhiteBalance = true; AutoExposure = true; // initialize texture parameters texture_ = new Texture2D(width_, height_, TextureFormat.ARGB32, false); pixels_ = texture_.GetPixels32(); pixels_handle_ = GCHandle.Alloc(pixels_, GCHandleType.Pinned); pixelsABGR_ = texture_.GetPixels32(); isReverse_ = is_reverse; }
private bool PixelHasAlpha(int x, int y, UnityEngine.Texture2D texture) { if (this.m_AlphaPixelCache == null) { this.m_AlphaPixelCache = new bool[texture.width * texture.height]; Color32[] pixels = texture.GetPixels32(); for (int i = 0; i < pixels.Length; i++) { this.m_AlphaPixelCache[i] = (pixels[i].a != 0); } } int num = y * texture.width + x; return(this.m_AlphaPixelCache[num]); }
static public int GetPixels32(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif int argc = LuaDLL.lua_gettop(l); if (argc == 1) { UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l); var ret = self.GetPixels32(); pushValue(l, true); pushValue(l, ret); return(2); } else if (argc == 2) { UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l); System.Int32 a1; checkType(l, 2, out a1); var ret = self.GetPixels32(a1); pushValue(l, true); pushValue(l, ret); return(2); } pushValue(l, false); LuaDLL.lua_pushstring(l, "No matched override function GetPixels32 to call"); return(2); } catch (Exception e) { return(error(l, e)); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif }
public static int GetPixels321_wrap(long L) { try { long nThisPtr = FCLibHelper.fc_get_inport_obj_ptr(L); UnityEngine.Texture2D obj = get_obj(nThisPtr); Color32[] ret = obj.GetPixels32(); long ret_ptr = FCLibHelper.fc_get_return_ptr(L); FCCustomParam.ReturnArray(ret, ret_ptr); } catch (Exception e) { Debug.LogException(e); } return(0); }
private bool PixelHasAlpha(int x, int y, UnityTexture2D texture) { if (m_AlphaPixelCache == null) { m_AlphaPixelCache = new bool[texture.width * texture.height]; Color32[] pixels = texture.GetPixels32(); for (int i = 0; i < pixels.Length; i++) { m_AlphaPixelCache[i] = pixels[i].a != 0; } } int index = y * (int)texture.width + x; return(m_AlphaPixelCache[index]); }
// Start is called before the first frame update public static void ImportDefaultTextures() { var assetManager = new AssetStudio.AssetsManager(); assetManager.LoadFiles(PhysicalFileSystem.Instance, Path.Combine(ConfigManager.AssetBundleSourcePath, "texture.ab")); var textures = assetManager.assetsFileList[0].Objects.OfType <AssetStudio.Texture2D>().ToArray(); if (textures.Length <= 0) { throw new Exception("Couldn't read default textures."); } try { for (int i = 0; i < textures.Length; i++) { var texture = textures[i]; EditorUtility.DisplayProgressBar("Texture import", "Importing default textures", (float)i / textures.Length); var textureData = texture.image_data.GetData(); var compressedTexture = new UnityEngine.Texture2D(texture.m_Width, texture.m_Height, (UnityEngine.TextureFormat)texture.m_TextureFormat, false); compressedTexture.LoadRawTextureData(textureData); compressedTexture.Apply(true); var pixels = compressedTexture.GetPixels32(); // We need to create an uncompressed texture to use ImageConversion.EncodeToPNG() var uncompressedTexture = new UnityEngine.Texture2D(texture.m_Width, texture.m_Height, UnityEngine.TextureFormat.RGBA32, false); uncompressedTexture.SetPixels32(pixels); var pngData = UnityEngine.ImageConversion.EncodeToPNG(uncompressedTexture); string path = $"Assets/Resources/DefaultTextures/{texture.m_Name}.png"; File.WriteAllBytes(path, pngData); AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate); UnityEngine.Object.DestroyImmediate(compressedTexture); UnityEngine.Object.DestroyImmediate(uncompressedTexture); } } finally { EditorUtility.ClearProgressBar(); } }
static int GetPixels32(IntPtr L) { int count = LuaDLL.lua_gettop(L); if (count == 1 && ToLua.CheckTypes(L, 1, typeof(UnityEngine.Texture2D))) { UnityEngine.Texture2D obj = (UnityEngine.Texture2D)ToLua.ToObject(L, 1); UnityEngine.Color32[] o = null; try { o = obj.GetPixels32(); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } ToLua.Push(L, o); return(1); } else if (count == 2 && ToLua.CheckTypes(L, 1, typeof(UnityEngine.Texture2D), typeof(int))) { UnityEngine.Texture2D obj = (UnityEngine.Texture2D)ToLua.ToObject(L, 1); int arg0 = (int)LuaDLL.lua_tonumber(L, 2); UnityEngine.Color32[] o = null; try { o = obj.GetPixels32(arg0); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } ToLua.Push(L, o); return(1); } else { LuaDLL.luaL_error(L, "invalid arguments to method: UnityEngine.Texture2D.GetPixels32"); } return(0); }
public static void GenerateRandom(this UnityEngine.Texture2D tex) { var pixels = tex.GetPixels32(); for (int y = 0; y < tex.height; ++y) { for (int x = 0; x < tex.width; ++x) { pixels[y * tex.width + x] = new Color(UnityEngine.Random.Range(0f, 1f), UnityEngine.Random.Range(0f, 1f), UnityEngine.Random.Range(0f, 1f), UnityEngine.Random.Range(0f, 1f)); } } tex.SetPixels32(pixels); tex.Apply(); }
public override Color32[] GetPixels32() { return(m_Texture.GetPixels32()); }