zxing barcode not displaying any text - barcode

I made Barcode generator using ZXing Library but when barcode generate then it wont display text below barcode like
try {
Map<EncodeHintType, Object> hints = null;
hints = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);
hints.put(EncodeHintType.CHARACTER_SET, "ABC-abc-1234");
BitMatrix bitMatrix = new Code128Writer().encode("ABC-abc-1234", BarcodeFormat.CODE_128, 350, 150, hints);
int width = bitMatrix.getWidth();
int height = bitMatrix.getHeight();
int[] pixels = new int[width * height];
// All are 0, or black, by default
for (int y = 0; y < height; y++) {
int offset = y * width;
for (int x = 0; x < width; x++) {
pixels[offset + x] = bitMatrix.get(x, y) ? Color.BLACK : Color.WHITE;
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
mImageView.setImageBitmap(bitmap);
} catch (Exception e) {
// TODO: handle exception
}

Maybe it's late to help you but I went through the same problem and was able to solve the following in a C#
var barcodeWriter = new BarcodeWriter
{
Format = BarcodeFormat.CODE_128,
Options = new EncodingOptions
{
Height = 160,
Width = 300,
Margin = 0,
PureBarcode = false
},
Renderer = new BitmapRenderer()
{
TextFont = new Font(FontFamily.GenericSerif, 15)
}
};
var bitmap = barcodeWriter.Write("your content");
bitmap.Save(#"C:\\FULL\PATH\FILE.JPG");

Related

How can I resize and compress an image file in Xamarin [duplicate]

I am working on xamarin.forms. I have to select images from gallery and then resize them and then upload them on server. But I don't know how I can resize selected image in a given particular size?
Please update me how I can do this?
This can be used with a stream (if you're using the Media Plugin https://github.com/jamesmontemagno/MediaPlugin) or standard byte arrays.
// If you already have the byte[]
byte[] resizedImage = await CrossImageResizer.Current.ResizeImageWithAspectRatioAsync(originalImageBytes, 500, 1000);
// If you have a stream, such as:
// var file = await CrossMedia.Current.PickPhotoAsync(options);
// var originalImageStream = file.GetStream();
byte[] resizedImage = await CrossImageResizer.Current.ResizeImageWithAspectRatioAsync(originalImageStream, 500, 1000);
I tried use CrossImageResizer.Current... but I did not find it in the Media Plugin. Instead I found an option called MaxWidthHeight, that worked only if you also add PhotoSize = PhotoSize.MaxWidthHeight option.
For Example :
var file = await CrossMedia.Current.PickPhotoAsync(new PickMediaOptions() { PhotoSize = PhotoSize.MaxWidthHeight, MaxWidthHeight = 600 });
var file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions { PhotoSize = PhotoSize.MaxWidthHeight, MaxWidthHeight = 600 });
Sadly enough there isn't a good cross-platform image resizer (that I've found at the time of this post). Image processing wasn't really designed to take place in a cross-platform environment for iOS and Android. It's much faster and cleaner to perform this on each platform using platform-specific code. You can do this using dependency injection and the DependencyService (or any other service or IOC).
AdamP gives a great response on how to do this Platform Specific Image Resizing
Here is the code taken from the link above.
iOS
public class MediaService : IMediaService
{
public byte[] ResizeImage(byte[] imageData, float width, float height)
{
UIImage originalImage = ImageFromByteArray(imageData);
var originalHeight = originalImage.Size.Height;
var originalWidth = originalImage.Size.Width;
nfloat newHeight = 0;
nfloat newWidth = 0;
if (originalHeight > originalWidth)
{
newHeight = height;
nfloat ratio = originalHeight / height;
newWidth = originalWidth / ratio;
}
else
{
newWidth = width;
nfloat ratio = originalWidth / width;
newHeight = originalHeight / ratio;
}
width = (float)newWidth;
height = (float)newHeight;
UIGraphics.BeginImageContext(new SizeF(width, height));
originalImage.Draw(new RectangleF(0, 0, width, height));
var resizedImage = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
var bytesImagen = resizedImage.AsJPEG().ToArray();
resizedImage.Dispose();
return bytesImagen;
}
}
Android
public class MediaService : IMediaService
{
public byte[] ResizeImage(byte[] imageData, float width, float height)
{
// Load the bitmap
BitmapFactory.Options options = new BitmapFactory.Options();// Create object of bitmapfactory's option method for further option use
options.InPurgeable = true; // inPurgeable is used to free up memory while required
Bitmap originalImage = BitmapFactory.DecodeByteArray(imageData, 0, imageData.Length, options);
float newHeight = 0;
float newWidth = 0;
var originalHeight = originalImage.Height;
var originalWidth = originalImage.Width;
if (originalHeight > originalWidth)
{
newHeight = height;
float ratio = originalHeight / height;
newWidth = originalWidth / ratio;
}
else
{
newWidth = width;
float ratio = originalWidth / width;
newHeight = originalHeight / ratio;
}
Bitmap resizedImage = Bitmap.CreateScaledBitmap(originalImage, (int)newWidth, (int)newHeight, true);
originalImage.Recycle();
using (MemoryStream ms = new MemoryStream())
{
resizedImage.Compress(Bitmap.CompressFormat.Png, 100, ms);
resizedImage.Recycle();
return ms.ToArray();
}
}
WinPhone
public class MediaService : IMediaService
{
private MediaImplementation mi = new MediaImplementation();
public byte[] ResizeImage(byte[] imageData, float width, float height)
{
byte[] resizedData;
using (MemoryStream streamIn = new MemoryStream(imageData))
{
WriteableBitmap bitmap = PictureDecoder.DecodeJpeg(streamIn, (int)width, (int)height);
float Height = 0;
float Width = 0;
float originalHeight = bitmap.PixelHeight;
float originalWidth = bitmap.PixelWidth;
if (originalHeight > originalWidth)
{
Height = height;
float ratio = originalHeight / height;
Width = originalWidth / ratio;
}
else
{
Width = width;
float ratio = originalWidth / width;
Height = originalHeight / ratio;
}
using (MemoryStream streamOut = new MemoryStream())
{
bitmap.SaveJpeg(streamOut, (int)Width, (int)Height, 0, 100);
resizedData = streamOut.ToArray();
}
}
return resizedData;
}
}
EDIT: If you are already using FFImageLoading in your project then you can just use that for your platform.
https://github.com/luberda-molinet/FFImageLoading
I fixed in my project, this was the best way for me .
when take photo or get image from gallery you can change size with properties
var file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
{
PhotoSize = PhotoSize.Custom,
CustomPhotoSize = 90 //Resize to 90% of original
});
for more information: https://github.com/jamesmontemagno/MediaPlugin

Move an object between two ml5js poseNet keypoints using p5js

I'm trying to make a circle move between two body keypoints – i.e between left and right shoulder. I started with this code to make an object following some position:
var rectLocation;
var x = 50;
var y = 50;
function setup() {
createCanvas(640,400);
rectLocation = createVector(width/2,height/2);
}
function draw() {
background(255);
var target = createVector(x,y);
var distance = target.dist(rectLocation);
var mappedDistance = map(distance, 100, 0, 1.5, 0.5);
target.sub(rectLocation);
target.normalize();
target.mult(mappedDistance);
rectLocation.add(target);
text('hello',rectLocation.x, rectLocation.y);
x = x + 1 ;
if (x > width) {
x = 50;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.3/p5.js"></script>
So with poseNet I converted x and y values of each keypoint into p5 Vectors and made one location follow another, but it doesn't seem to move and I can't get why. Sketch: https://editor.p5js.org/sebyakin/sketches/LQ7gqwGZH and my code here:
let video;
let poseNet;
let noseX = 0;
let noseY = 0;
let eyelX = 0;
let eyelY = 0;
let shoulderX = 0;
let shoulderY = 0;
let firstLocation;
let target;
function setup() {
createCanvas(640, 480);
video = createCapture(VIDEO);
video.hide();
poseNet = ml5.poseNet(video, modelReady);
poseNet.on('pose', gotPoses);
// creating empty vectors
firstLocation = createVector(0,0);
target = createVector(0,0);
}
function gotPoses(poses) {
if (poses.length > 0) {
let nX = poses[0].pose.keypoints[0].position.x;
let nY = poses[0].pose.keypoints[0].position.y;
let eX = poses[0].pose.keypoints[1].position.x;
let eY = poses[0].pose.keypoints[1].position.y;
let sX = poses[0].pose.keypoints[5].position.x;
let sY = poses[0].pose.keypoints[5].position.y;
noseX = nX;
noseY = nY;
eyelX = eX;
eyelY = eY;
shoulderX = sX;
shoulderY = sY;
}
}
function modelReady() {
console.log('model ready');
}
function draw() {
image(video, 0, 0);
fill(0,0,255);
// set vectors to keypoints values
firstLocation.set(noseX, noseY);
target.set(shoulderX, shoulderY)
// make a circle follow target loaction
let distance = target.dist(firstLocation);
let mappedDistance = map(distance, 100, 0, 1.5, 0.5);
target.sub(firstLocation);
// target.normalize();
// target.mult(mappedDistance);
firstLocation.add(target);
ellipse(firstLocation.x, firstLocation.y, 50);
console.log(target.x);
}
Where did I go wrong?

How to use UrhoSharp 3D Moving Imageview in xamarin forms

async void CreateScene()
{
Input.SubscribeToTouchEnd(OnTouched);
//want add image view in UrhoSharp Surface for rotatable and 3D image
var imageview = new Xamarin.Forms.Image { Source = "icon.", HeightRequest = 150, WidthRequest = 150 };
scene = new Scene();
octree = scene.CreateComponent<Octree>();
plotNode = scene.CreateChild();
var baseNode = plotNode.CreateChild().CreateChild();
var plane = baseNode.CreateComponent<StaticModel>();
plane.Model = CoreAssets.Models.Plane;
var cameraNode = scene.CreateChild();
camera = cameraNode.CreateComponent<Camera>();
cameraNode.Position = new Vector3(10, 15, 10) / 1.75f;
cameraNode.Rotation = new Quaternion(-0.121f, 0.878f, -0.305f, -0.35f);
Node lightNode = cameraNode.CreateChild();
var light = lightNode.CreateComponent<Light>();
light.LightType = LightType.Point;
light.Range = 100;
light.Brightness = 1.3f;
int size = 3;
baseNode.Scale = new Vector3(size * 1.5f, 1, size * 1.5f);
bars = new List<Bar>(size * size);
for (var i = 0f; i < size * 1.5f; i += 1.5f)
{
for (var j = 0f; j < size * 1.5f; j += 1.5f)
{
var boxNode = plotNode.CreateChild();
boxNode.Position = new Vector3(size / 2f - i, 0, size / 2f - j);
var box = new Bar(new Color(RandomHelper.NextRandom(), RandomHelper.NextRandom(), RandomHelper.NextRandom(), 0.9f));
boxNode.AddComponent(box);
box.SetValueWithAnimation((Math.Abs(i) + Math.Abs(j) + 1) / 2f);
bars.Add(box);
}
}
SelectedBar = bars.First();
SelectedBar.Select();
try
{
await plotNode.RunActionsAsync(new EaseBackOut(new RotateBy(2f, 0, 360, 0)));
}
catch (OperationCanceledException) { }
movementsEnabled = true;
}

Xamarin iOS: How to change the color of a UIImage pixel by pixel

Sorry if this has already been answered somewhere but I could not find it.
Basically, I am receiving a QR code where the code itself is black and the background is white (this is a UIImage). I would like to change to the color of the white background to transparent or a custom color and change the QRCode color from black to white. (In Xamarin iOS)
I already know how to get the color of a specific Pixel using the following code:
static UIColor GetPixelColor(CGBitmapContext context, byte[] rawData,
UIImage barcode, CGPoint pt)
{
var handle = GCHandle.Alloc(rawData);
UIColor resultColor = null;
using (context)
{
context.DrawImage(new CGRect(-pt.X, pt.Y - barcode.Size.Height,
barcode.Size.Width, barcode.Size.Height), barcode.CGImage);
float red = (rawData[0]) / 255.0f;
float green = (rawData[1]) / 255.0f;
float blue = (rawData[2]) / 255.0f;
float alpha = (rawData[3]) / 255.0f;
resultColor = UIColor.FromRGBA(red, green, blue, alpha);
}
return resultColor;
}
This is currently my function:
static UIImage GetRealQRCode(UIImage barcode)
{
int width = (int)barcode.Size.Width;
int height = (int)barcode.Size.Height;
var bytesPerPixel = 4;
var bytesPerRow = bytesPerPixel * width;
var bitsPerComponent = 8;
var colorSpace = CGColorSpace.CreateDeviceRGB();
var rawData = new byte[bytesPerRow * height];
CGBitmapContext context = new CGBitmapContext(rawData, width,
height, bitsPerComponent, bytesPerRow, colorSpace,
CGImageAlphaInfo.PremultipliedLast);
for (int i = 0; i < rawData.Length; i++)
{
for (int j = 0; j < bytesPerRow; j++)
{
CGPoint pt = new CGPoint(i, j);
UIColor currentColor = GetPixelColor(context, rawData,
barcode, pt);
}
}
}
Anyone know how to do this ?
Thanks in advance !
Assuming your UIImage is backed by a CGImage (and not a CIImage):
var cgImage = ImageView1.Image.CGImage; // Your UIImage with a CGImage backing image
var bytesPerPixel = 4;
var bitsPerComponent = 8;
var bytesPerUInt32 = sizeof(UInt32) / sizeof(byte);
var width = cgImage.Width;
var height = cgImage.Height;
var bytesPerRow = bytesPerPixel * cgImage.Width;
var numOfBytes = cgImage.Height * cgImage.Width * bytesPerUInt32;
IntPtr pixelPtr = IntPtr.Zero;
try
{
pixelPtr = Marshal.AllocHGlobal((int)numOfBytes);
using (var colorSpace = CGColorSpace.CreateDeviceRGB())
{
CGImage newCGImage;
using (var context = new CGBitmapContext(pixelPtr, width, height, bitsPerComponent, bytesPerRow, colorSpace, CGImageAlphaInfo.PremultipliedLast))
{
context.DrawImage(new CGRect(0, 0, width, height), cgImage);
unsafe
{
var currentPixel = (byte*)pixelPtr.ToPointer();
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
// RGBA8888 pixel format
if (*currentPixel == byte.MinValue)
{
*currentPixel = byte.MaxValue;
*(currentPixel + 1) = byte.MaxValue;
*(currentPixel + 2) = byte.MaxValue;
}
else
{
*currentPixel = byte.MinValue;
*(currentPixel + 1) = byte.MinValue;
*(currentPixel + 2) = byte.MinValue;
*(currentPixel + 3) = byte.MinValue;
}
currentPixel += 4;
}
}
}
newCGImage = context.ToImage();
}
var uiimage = new UIImage(newCGImage);
imageView2.Image = uiimage; // Do something with your new UIImage
}
}
finally
{
if (pixelPtr != IntPtr.Zero)
Marshal.FreeHGlobal(pixelPtr);
}
If you do not actually need access to the individual pixels but the end result only, using CoreImage pre-exisitng filters you can first invert the colors and then use the black pixels as an alpha mask. Otherwise see my other answer using Marshal.AllocHGlobal and pointers.
using (var coreImage = new CIImage(ImageView1.Image))
using (var invertFilter = CIFilter.FromName("CIColorInvert"))
{
invertFilter.Image = coreImage;
using (var alphaMaskFiter = CIFilter.FromName("CIMaskToAlpha"))
{
alphaMaskFiter.Image = invertFilter.OutputImage;
var newCoreImage = alphaMaskFiter.OutputImage;
var uiimage = new UIImage(newCoreImage);
imageView2.Image = uiimage; // Do something with your new UIImage
}
}
The plus side is this is blazing fast ;-) and the results are the same:
If you need even faster processing assuming you are batch converting a number of these images, you can write a custom CIKernel that incorporates these two filters into one kernel and thus only process the image once.
Xamarin.IOS with this method you can convert all color white to transparent for me only works with files ".jpg" with .png doesn't work but you can convert the files to jpg and call this method.
public static UIImage ProcessImage (UIImage image)
{
CGImage rawImageRef = image.CGImage;
nfloat[] colorMasking = new nfloat[6] { 222, 255, 222, 255, 222, 255 };
CGImage imageRef = rawImageRef.WithMaskingColors(colorMasking);
UIImage imageB = UIImage.FromImage(imageRef);
return imageB;
}
Regards

How To Capture the color from screen in mouse position using Unity and C#?

I did not find a direct function in Color section or since there is no direct C# Unity function for picking the color from post render. How is the best approach for picking the color in the mouse position?
I have done research and looks like there is posible to make a screenshot and then look into the texture calculating the mouse position.
Input.GetMouseButtonDown(0)
Application.CaptureScreenshot("Screenshot.png");
// get the color pixel in the same coordinates of the mouse position
Vector3 mouseCoordinates = Input.mousePosition;
myFinalColor = tex.GetPixel((int)mouseCoordinates.x, (int)mouseCoordinates.y);
Or do I have to make a second camera and attach it to a mesh render?
You just need to use GetPixel(x,y)
This is very simple.
Save Screenshot to Texture2D for example MyTexture
And add .GetPixel( x postion of moue , Y position of mouse )
Save it to your color for GetScreenShot ( make your View to Texture2D )
Color TheColorPicked;
if (Input.GetMouseButtonDown(0))
{
TheColorPicked = MyTexture.GetPixel(Input.mousePosition.x,
Input.mousePosition.y);
}
Yes you can make your own colour picker. Here is the code thanks to Git-hub this page.
using UnityEngine;
using System.Collections;
// relies on: http://forum.unity3d.com/threads/12031-create-random-colors?p=84625&viewfull=1#post84625
public class ColorPicker : MonoBehaviour {
public bool useDefinedPosition = false;
public int positionLeft = 0;
public int positionTop = 0;
// the solid texture which everything is compared against
public Texture2D colorPicker;
// the picker being displayed
private Texture2D displayPicker;
// the color that has been chosen
public Color setColor;
private Color lastSetColor;
public bool useDefinedSize = false;
public int textureWidth = 360;
public int textureHeight = 120;
private float saturationSlider = 0.0F;
private Texture2D saturationTexture;
private Texture2D styleTexture;
public bool showPicker = false;
void Awake() {
if (!useDefinedPosition) {
positionLeft = (Screen.width / 2) - (textureWidth / 2);
positionTop = (Screen.height / 2) - (textureHeight / 2);
}
// if a default color picker texture hasn't been assigned, make one dynamically
if (!colorPicker) {
colorPicker = new Texture2D(textureWidth, textureHeight, TextureFormat.ARGB32, false);
ColorHSV hsvColor;
for (int i = 0; i < textureWidth; i++) {
for (int j = 0; j < textureHeight; j++) {
hsvColor = new ColorHSV((float)i, (1.0f / j) * textureHeight, 1.0f);
colorPicker.SetPixel(i, j, hsvColor.ToColor());
}
}
}
colorPicker.Apply();
displayPicker = colorPicker;
if (!useDefinedSize) {
textureWidth = colorPicker.width;
textureHeight = colorPicker.height;
}
float v = 0.0F;
float diff = 1.0f / textureHeight;
saturationTexture = new Texture2D(20, textureHeight);
for (int i = 0; i < saturationTexture.width; i++) {
for (int j = 0; j < saturationTexture.height; j++) {
saturationTexture.SetPixel(i, j, new Color(v, v, v));
v += diff;
}
v = 0.0F;
}
saturationTexture.Apply();
// small color picker box texture
styleTexture = new Texture2D(1, 1);
styleTexture.SetPixel(0, 0, setColor);
}
void OnGUI(){
if (!showPicker) return;
GUI.Box(new Rect(positionLeft - 3, positionTop - 3, textureWidth + 60, textureHeight + 60), "");
if (GUI.RepeatButton(new Rect(positionLeft, positionTop, textureWidth, textureHeight), displayPicker)) {
int a = (int)Input.mousePosition.x;
int b = Screen.height - (int)Input.mousePosition.y;
setColor = displayPicker.GetPixel(a - positionLeft, -(b - positionTop));
lastSetColor = setColor;
}
saturationSlider = GUI.VerticalSlider(new Rect(positionLeft + textureWidth + 3, positionTop, 10, textureHeight), saturationSlider, 1, -1);
setColor = lastSetColor + new Color(saturationSlider, saturationSlider, saturationSlider);
GUI.Box(new Rect(positionLeft + textureWidth + 20, positionTop, 20, textureHeight), saturationTexture);
if (GUI.Button(new Rect(positionLeft + textureWidth - 60, positionTop + textureHeight + 10, 60, 25), "Apply")) {
setColor = styleTexture.GetPixel(0, 0);
// hide picker
showPicker = false;
}
// color display
GUIStyle style = new GUIStyle();
styleTexture.SetPixel(0, 0, setColor);
styleTexture.Apply();
style.normal.background = styleTexture;
GUI.Box(new Rect(positionLeft + textureWidth + 10, positionTop + textureHeight + 10, 30, 30), new GUIContent(""), style);
}
}
You can also find this helpfull asset store packages 1 2.

Resources