Last active
August 29, 2015 14:16
-
-
Save setchi/c31ac739a1d0be250a9f to your computer and use it in GitHub Desktop.
画像を分割して個別に保存する
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.IO; | |
public class ImageSlicer : MonoBehaviour { | |
[SerializeField] | |
Texture2D texture; | |
[SerializeField] | |
int horizontalSlices; | |
[SerializeField] | |
int verticalSlices; | |
[SerializeField] | |
string saveDirectoryPath = "slicedImages/"; | |
int partWidth; | |
int partHeight; | |
void Start () { | |
// 保存先ディレクトリが存在しなければ作成 | |
if (!Directory.Exists(saveDirectoryPath)) | |
Directory.CreateDirectory(saveDirectoryPath); | |
SliceImage(); | |
} | |
void SliceImage() { | |
partWidth = texture.width / horizontalSlices; | |
partHeight = texture.height / verticalSlices; | |
var fileNameIndex = 0; | |
for (var partY = verticalSlices; partY > 0; partY--) { | |
for (var partX = 0; partX < horizontalSlices; partX++) { | |
// 分割した一枚分のピクセルたちを取得 | |
var partPixels = ReadPartPixels(partX, partY, texture); | |
// 新しいテクスチャに書き込む | |
var partTexture = new Texture2D (partWidth, partHeight, TextureFormat.RGBA32, false); | |
partTexture.SetPixels (partPixels); | |
partTexture.Apply (); | |
// テクスチャをpngにしてローカルに保存 | |
SaveBinaryToLocal (partTexture.EncodeToPNG(), fileNameIndex + ".png"); | |
fileNameIndex++; | |
} | |
} | |
} | |
Color[] ReadPartPixels(int partX, int partY, Texture2D texture) { | |
var pixels = new Color[partWidth * partHeight]; | |
var offsetX = partX * partWidth; | |
var offsetY = partY * partHeight; | |
for (int y = offsetY, y_ = partHeight - 1; y > offsetY - partHeight; y--, y_--) { | |
for (int x = offsetX, x_ = 0; x < offsetX + partWidth; x++, x_++) { | |
pixels[y_ * partWidth + x_] = texture.GetPixel(x, y); | |
} | |
} | |
return pixels; | |
} | |
void SaveBinaryToLocal(byte[] binaryData, string fileName) { | |
var fileStream = new FileStream (saveDirectoryPath + fileName, FileMode.Create, FileAccess.Write); | |
var binaryWriter = new BinaryWriter (fileStream); | |
binaryWriter.Write(binaryData); | |
binaryWriter.Close(); | |
fileStream.Close(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment